56419d192b33bd8df28104807fb663c33e64b15b
[mir.git] / source / mir / servlet / ServletModule.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mir.servlet;
33
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Locale;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.servlet.http.HttpSession;
43
44 import mir.config.MirPropertiesConfiguration;
45 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
46 import mir.entity.EntityList;
47 import mir.log.LoggerWrapper;
48 import mir.misc.HTMLParseException;
49 import mir.misc.HTMLTemplateProcessor;
50 import mir.misc.LineFilterWriter;
51 import mir.module.AbstractModule;
52 import mir.module.ModuleException;
53 import mir.storage.StorageObject;
54 import mir.storage.StorageObjectFailure;
55 import freemarker.template.SimpleHash;
56 import freemarker.template.TemplateModelRoot;
57
58
59 /**
60  * Abstract class ServletModule provides the base functionality for servlets.
61  * Deriving a class from ServletModule enables class to insert/edit/update/delete
62  * and list Entity from a Database via mainModule.
63  *
64  *
65  *  Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der
66  *  abgeleiteten ServletModule zur Verf?gung.
67  *
68  * @version 28.6.1999
69  * @author RK
70  */
71
72 public abstract class ServletModule {
73
74   public String defaultAction;
75   protected LoggerWrapper logger;
76         protected MirPropertiesConfiguration configuration;
77   protected AbstractModule mainModule;
78   protected String templateListString;
79   protected String templateObjektString;
80   protected String templateConfirmString;
81   
82   
83   public ServletModule(){
84     try {
85       configuration = MirPropertiesConfiguration.instance();
86     } catch (PropertiesConfigExc e) {
87       e.printStackTrace(System.err);
88     }
89   }
90   
91
92   /**
93    * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden.
94    * @return ServletModule
95    */
96   public static ServletModule getInstance() {
97     return null;
98   }
99
100   /**
101    * get the module name to be used for generic operations like delete.
102    */
103   protected String getOperationModuleName() {
104     return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
105   }
106
107   /**
108    * get the session binded language
109    */
110   public String getLanguage(HttpServletRequest req) {
111     HttpSession session = req.getSession(false);
112     String language = (String) session.getAttribute("Language");
113     if (language == null) {
114       language = configuration.getString("StandardLanguage");
115     }
116     return language;
117   }
118
119   /**
120    * get the locale either from the session or the accept-language header ot the request
121    * this supersedes getLanguage for the new i18n
122    */
123   public Locale getLocale(HttpServletRequest req) {
124     Locale loc = null;
125     HttpSession session = req.getSession(false);
126     if (session != null) {
127       // session can be null in case of logout
128       loc = (Locale) session.getAttribute("Locale");
129     }
130     // if there is nothing in the session get it fron the accept-language
131     if (loc == null) {
132       loc = req.getLocale();
133     }
134     return loc;
135   }
136
137   public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleException {
138     try {
139       aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery);
140     }
141     catch (Throwable t) {
142       throw new ServletModuleException(t.getMessage());
143     }
144   }
145
146   /**
147    *  list(req,res) - generische Listmethode. Wennn die Funktionalitaet
148    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
149    *  ueberschreiben werden.
150    *
151    * @param req Http-Request, das vom Dispatcher durchgereicht wird
152    * @param res Http-Response, die vom Dispatcher durchgereicht wird
153    */
154   public void list(HttpServletRequest req, HttpServletResponse res)
155       throws ServletModuleException {
156     try {
157       EntityList theList;
158       String offsetParam = req.getParameter("offset");
159       int offset = 0;
160       PrintWriter out = res.getWriter();
161
162       // hier offsetcode bearbeiten
163       if (offsetParam != null && !offsetParam.equals("")) {
164         offset = Integer.parseInt(offsetParam);
165       }
166       if (req.getParameter("next") != null) {
167         offset = Integer.parseInt(req.getParameter("nextoffset"));
168       }
169       else {
170         if (req.getParameter("prev") != null) {
171           offset = Integer.parseInt(req.getParameter("prevoffset"));
172         }
173       }
174       theList = mainModule.getByWhereClause(null, offset);
175
176       HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req));
177     }
178     catch (Exception e) {
179       throw new ServletModuleException(e.getMessage());
180     }
181   }
182
183   /**
184    *  add(req,res) - generische Addmethode. Wennn die Funktionalitaet
185    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
186    *  ueberschreiben werden.
187    * @param req Http-Request, das vom Dispatcher durchgereicht wird
188    * @param res Http-Response, die vom Dispatcher durchgereicht wird
189    */
190   public void add(HttpServletRequest req, HttpServletResponse res)
191       throws ServletModuleException {
192
193     try {
194       SimpleHash mergeData = new SimpleHash();
195       mergeData.put("new", "1");
196       deliver(req, res, mergeData, templateObjektString);
197     }
198     catch (Exception e) {
199       throw new ServletModuleException(e.getMessage());
200     }
201   }
202
203   /**
204    *  insert(req,res) - generische Insertmethode, folgt auf add.
205    *  Wennn die Funktionalitaet
206    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
207    *  ueberschreiben werden.
208    *
209    * @param req Http-Request, das vom Dispatcher durchgereicht wird
210    * @param res Http-Response, die vom Dispatcher durchgereicht wird
211    */
212   public void insert(HttpServletRequest req, HttpServletResponse res)
213       throws ServletModuleException, ServletModuleUserException {
214     try {
215       HashMap withValues = getIntersectingValues(req, mainModule.getStorageObject());
216       logger.debug("--trying to add...");
217       String id = mainModule.add(withValues);
218       logger.debug("--trying to deliver..." + id);
219       list(req, res);
220     }
221     catch (Exception e) {
222       throw new ServletModuleException(e.getMessage());
223     }
224   }
225
226   /**
227    *  delete(req,res) - generic delete method. Can be overridden in subclasses.
228    *
229    */
230
231   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {
232     try {
233       String idParam = req.getParameter("id");
234
235       if (idParam == null)
236         throw new ServletModuleException("Invalid call to delete: no id supplied");
237
238       String confirmParam = req.getParameter("confirm");
239       String cancelParam = req.getParameter("cancel");
240       if (confirmParam == null && cancelParam == null) {
241         SimpleHash mergeData = new SimpleHash();
242
243         mergeData.put("module", getOperationModuleName());
244         mergeData.put("infoString", getOperationModuleName() + ": " + idParam);
245         mergeData.put("id", idParam);
246         mergeData.put("where", req.getParameter("where"));
247         mergeData.put("order", req.getParameter("order"));
248         mergeData.put("offset", req.getParameter("offset"));
249         // this stuff is to be compatible with the other more advanced
250         // search method used for media and comments
251         mergeData.put("query_media_folder", req.getParameter("query_media_folder"));
252         mergeData.put("query_is_published", req.getParameter("query_is_published"));
253         mergeData.put("query_text", req.getParameter("query_text"));
254         mergeData.put("query_field", req.getParameter("query_field"));
255
256         deliver(req, res, mergeData, templateConfirmString);
257       }
258       else {
259         if (confirmParam != null && !confirmParam.equals("")) {
260           //theLog.printInfo("delete confirmed!");
261           mainModule.deleteById(idParam);
262           list(req, res); // back to list
263         }
264         else {
265           if (req.getParameter("where") != null)
266             list(req, res);
267           else
268             edit(req, res);
269         }
270       }
271     }
272     catch (Exception e) {
273       throw new ServletModuleException(e.getMessage());
274     }
275   }
276
277   /**
278    *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet
279    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
280    *  ueberschreiben werden.
281    *
282    * @param req Http-Request, das vom Dispatcher durchgereicht wird
283    * @param res Http-Response, die vom Dispatcher durchgereicht wird
284    */
285   public void edit(HttpServletRequest req, HttpServletResponse res)
286       throws ServletModuleException {
287     try {
288       String idParam = req.getParameter("id");
289       deliver(req, res, mainModule.getById(idParam), templateObjektString);
290     }
291     catch (ModuleException e) {
292       throw new ServletModuleException(e.getMessage());
293     }
294   }
295
296   /**
297    *  update(req,res) - generische Updatemethode. Wennn die Funktionalitaet
298    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
299    *  ueberschreiben werden.
300    *
301    * @param req Http-Request, das vom Dispatcher durchgereicht wird
302    * @param res Http-Response, die vom Dispatcher durchgereicht wird
303    */
304
305   public void update(HttpServletRequest req, HttpServletResponse res)
306       throws ServletModuleException {
307     try {
308       String idParam = req.getParameter("id");
309       HashMap withValues = getIntersectingValues(req, mainModule.getStorageObject());
310
311       String id = mainModule.set(withValues);
312       String whereParam = req.getParameter("where");
313       String orderParam = req.getParameter("order");
314
315       if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) {
316         list(req, res);
317       }
318       else {
319         edit(req, res);
320       }
321     }
322     catch (Exception e) {
323       throw new ServletModuleException(e.getMessage());
324     }
325   }
326
327   /**
328    * deliver liefert das Template mit dem Filenamen templateFilename
329    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
330    * TemplateModelRoot rtm gemischt wurde
331    *
332    * @param res Http-Response, die vom Dispatcher durchgereicht wird
333    * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
334    *   Daten, die ins Template gemerged werden sollen.
335    * @param tmpl Name des Templates
336    * @exception ServletModuleException
337    */
338   public void deliver(HttpServletRequest req, HttpServletResponse res,
339                       TemplateModelRoot rtm, TemplateModelRoot popups,
340                       String templateFilename)
341       throws ServletModuleException {
342     if (rtm == null) rtm = new SimpleHash();
343     try {
344       PrintWriter out = res.getWriter();
345       HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req));
346
347       // we default to admin bundles here, which is not exactly beautiful...
348       // but this whole producer stuff is going to be rewritten soon.
349       // ServletModuleOpenIndy overwrites deliver() to use open bundles
350       // (br1)
351       out.close();
352     }
353     catch (HTMLParseException e) {
354       throw new ServletModuleException(e.getMessage());
355     } catch (IOException e) {
356       throw new ServletModuleException(e.getMessage());
357     }
358   }
359
360
361   /**
362    * deliver liefert das Template mit dem Filenamen templateFilename
363    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
364    * TemplateModelRoot rtm gemischt wurde
365    *
366    * @param res Http-Response, die vom Dispatcher durchgereicht wird
367    * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
368    *   Daten, die ins Template gemerged werden sollen.
369    * @param tmpl Name des Templates
370    * @exception ServletModuleException
371    */
372   public void deliver(HttpServletRequest req, HttpServletResponse res,
373                       TemplateModelRoot rtm, String templateFilename)
374       throws ServletModuleException {
375     deliver(req, res, rtm, null, templateFilename);
376   }
377
378   /**
379    * deliver liefert das Template mit dem Filenamen templateFilename
380    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
381    * TemplateModelRoot rtm gemischt wurde
382    *
383    * @param res Http-Response, die vom Dispatcher durchgereicht wird
384    * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
385    *   Daten, die ins Template gemerged werden sollen.
386    * @param tmpl Name des Templates
387    * @exception ServletModuleException
388    */
389   public void deliver_compressed(HttpServletRequest req, HttpServletResponse res,
390                                  TemplateModelRoot rtm, String templateFilename)
391       throws ServletModuleException {
392     if (rtm == null) rtm = new SimpleHash();
393     try {
394       PrintWriter out = new LineFilterWriter(res.getWriter());
395       //PrintWriter out =  res.getWriter();
396       HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));
397       out.close();
398     }
399     catch (HTMLParseException e) {
400       throw new ServletModuleException(e.getMessage());
401     }
402     catch (IOException e) {
403       throw new ServletModuleException(e.getMessage());
404     }
405   }
406
407   /**
408    * deliver liefert das Template mit dem Filenamen templateFilename
409    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
410    * TemplateModelRoot rtm gemischt wurde
411    *
412    * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen.
413    * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
414    *   Daten, die ins Template gemerged werden sollen.
415    * @param tmpl Name des Templates
416    * @exception ServletModuleException
417    */
418   private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out,
419                        TemplateModelRoot rtm, String templateFilename)
420       throws HTMLParseException {
421     HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));
422   }
423
424   /**
425    *  Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem
426    *  Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des
427    *  doParameters ausgefuehrt.
428    *
429    * @return Name der Default-Action
430    */
431   public String defaultAction() {
432     return defaultAction;
433   }
434
435   /**
436    *  Hier kann vor der Datenaufbereitung schon mal ein response geschickt
437    *  werden (um das subjektive Antwortverhalten bei langsamen Verbindungen
438    *  zu verbessern).
439    */
440   public void predeliver(HttpServletRequest req, HttpServletResponse res) {
441     ;
442   }
443
444   /**
445    * Holt die Felder aus der Metadatenfelderliste des StorageObjects, die
446    * im HttpRequest vorkommen und liefert sie als HashMap zurueck
447    *
448    * @return HashMap mit den Werten
449    */
450   public HashMap getIntersectingValues(HttpServletRequest req, StorageObject theStorage)
451       throws ServletModuleException {
452     ArrayList theFieldList;
453     try {
454       theFieldList = theStorage.getFields();
455     }
456     catch (StorageObjectFailure e) {
457       throw new ServletModuleException("ServletModule.getIntersectingValues: " + e.getMessage());
458     }
459
460     HashMap withValues = new HashMap();
461     String aField, aValue;
462
463     for (int i = 0; i < theFieldList.size(); i++) {
464       aField = (String) theFieldList.get(i);
465       aValue = req.getParameter(aField);
466       if (aValue != null) withValues.put(aField, aValue);
467     }
468     return withValues;
469   }
470
471 }