support added for local additions to admin.properties
[mir.git] / source / mir / servlet / ServletModule.java
index d276b78..f3f008b 100755 (executable)
@@ -1,25 +1,64 @@
 /*
- * put your module comment here
+ * Copyright (C) 2001, 2002  The Mir-coders group
  *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
  */
 
+package mir.servlet;
+
+import freemarker.template.SimpleHash;
+import freemarker.template.TemplateModelRoot;
+import freemarker.template.TemplateModel;
 
-package  mir.servlet;
+import mir.entity.EntityList;
+import mir.log.*;
+import mir.misc.*;
+import mir.module.AbstractModule;
+import mir.module.ModuleException;
+import mir.storage.StorageObject;
+import mir.storage.StorageObjectException;
 
-import  java.io.*;
-import  java.lang.*;
-import  java.util.*;
-import  javax.servlet.http.*;
-import  freemarker.template.*;
-import  mir.storage.*;
-import  mir.servlet.ServletModuleException;
-import  mir.misc.*;
-import  mir.entity.*;
-import  mir.module.*;
-import  mir.misc.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Locale;
 
 
 /**
+ * Abstract class ServletModule provides the base functionality for servlets.
+ * Deriving a class from ServletModule enables class to insert/edit/update/delete
+ * and list Entity from a Database via mainModule.
+ *
+ *
  *  Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der
  *  abgeleiteten ServletModule zur Verfügung.
  *
@@ -29,35 +68,67 @@ import  mir.misc.*;
 
 public abstract class ServletModule {
 
-  public String                 defaultAction;
-  protected Logfile             theLog;
-  protected AbstractModule      mainModule;
-  protected String              templateListString;
-  protected String              templateObjektString;
-  protected String              templateConfirmString;
+  public String defaultAction;
+  protected LoggerWrapper logger;
+
+  protected AbstractModule mainModule;
+  protected String templateListString;
+  protected String templateObjektString;
+  protected String templateConfirmString;
 
   /**
    * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden.
    * @return ServletModule
    */
-  public static ServletModule getInstance() { return null; }
+  public static ServletModule getInstance() {
+    return null;
+  }
+
+  /**
+   * get the module name to be used for generic operations like delete.
+   */
+  protected String getOperationModuleName() {
+    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
+  }
 
   /**
    * get the session binded language
    */
-  public String getLanguage(HttpServletRequest req){
-    HttpSession session = req.getSession(true);
-    String language = (String)session.getAttribute("Language");
-    if(language==null){
-      language=Configuration.getProperty("StandardLanguage");
+  public String getLanguage(HttpServletRequest req) {
+    HttpSession session = req.getSession(false);
+    String language = (String) session.getAttribute("Language");
+    if (language == null) {
+      language = MirConfig.getProp("StandardLanguage");
     }
     return language;
   }
 
-  // ACHTUNG DEPRECATED::::
-  public void process(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {}
-
+  /**
+   * get the locale either from the session or the accept-language header ot the request
+   * this supersedes getLanguage for the new i18n
+   */
+  public Locale getLocale(HttpServletRequest req) {
+    Locale loc = null;
+    HttpSession session = req.getSession(false);
+    if (session != null) {
+      // session can be null in case of logout
+      loc = (Locale) session.getAttribute("Locale");
+    }
+    // if there is nothing in the session get it fron the accept-language
+    if (loc == null) {
+      loc = req.getLocale();
+    }
+    return loc;
+  }
 
+  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleException {
+    try {
+      aResponse.sendRedirect(MirConfig.getProp("RootUri") + "/Mir?"+aQuery);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleException(t.getMessage());
+    }
+  }
 
   /**
    *  list(req,res) - generische Listmethode. Wennn die Funktionalitaet
@@ -68,33 +139,31 @@ public abstract class ServletModule {
    * @param res Http-Response, die vom Dispatcher durchgereicht wird
    */
   public void list(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException {
+      throws ServletModuleException {
     try {
-      EntityList   theList;
-      String       offsetParam = req.getParameter("offset");
-      int          offset=0;
+      EntityList theList;
+      String offsetParam = req.getParameter("offset");
+      int offset = 0;
       PrintWriter out = res.getWriter();
 
       // hier offsetcode bearbeiten
-      if (offsetParam != null && !offsetParam.equals("")){
+      if (offsetParam != null && !offsetParam.equals("")) {
         offset = Integer.parseInt(offsetParam);
       }
-      if (req.getParameter("next") != null){
-          offset=Integer.parseInt(req.getParameter("nextoffset"));
-      } else {
-          if (req.getParameter("prev") != null){
-            offset = Integer.parseInt(req.getParameter("prevoffset"));
-          }
+      if (req.getParameter("next") != null) {
+        offset = Integer.parseInt(req.getParameter("nextoffset"));
       }
-      theList = mainModule.getByWhereClause(null, offset);
-      //theList = mainModule.getByWhereClause((String)null, offset);
-      if (theList == null || theList.getCount() == 0 || theList.getCount()>1){
-        HTMLTemplateProcessor.process(res,getLanguage(req)+"/"+templateListString, theList, out);
-      } else {
-        deliver(req, res, theList.elementAt(0), templateObjektString);
+      else {
+        if (req.getParameter("prev") != null) {
+          offset = Integer.parseInt(req.getParameter("prevoffset"));
+        }
       }
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
+      theList = mainModule.getByWhereClause(null, offset);
+
+      HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req));
+    }
+    catch (Exception e) {
+      throw new ServletModuleException(e.getMessage());
     }
   }
 
@@ -106,14 +175,15 @@ public abstract class ServletModule {
    * @param res Http-Response, die vom Dispatcher durchgereicht wird
    */
   public void add(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException {
+      throws ServletModuleException {
 
     try {
       SimpleHash mergeData = new SimpleHash();
       mergeData.put("new", "1");
       deliver(req, res, mergeData, templateObjektString);
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
+    }
+    catch (Exception e) {
+      throw new ServletModuleException(e.getMessage());
     }
   }
 
@@ -127,62 +197,60 @@ public abstract class ServletModule {
    * @param res Http-Response, die vom Dispatcher durchgereicht wird
    */
   public void insert(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException {
+      throws ServletModuleException, ServletModuleUserException {
     try {
       HashMap withValues = getIntersectingValues(req, mainModule.getStorageObject());
+      logger.debug("--trying to add...");
       String id = mainModule.add(withValues);
-      // theLog.printDebugInfo("--trying to deliver..."+id);
-      list(req,res);
-      //deliver(req, res, mainModule.getById(id), templateObjektString);
+      logger.debug("--trying to deliver..." + id);
+      list(req, res);
+    }
+    catch (Exception e) {
+      throw new ServletModuleException(e.getMessage());
     }
-    catch (Exception e) { throw new ServletModuleException(e.toString());}
   }
 
-/**
-   *  delete(req,res) - generische Deletemethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
+  /**
+   *  delete(req,res) - generic delete method. Can be overridden in subclasses.
    *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
    */
 
-  public void delete(HttpServletRequest req, HttpServletResponse res)
-  throws ServletModuleException
-  {
+  public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {
     try {
       String idParam = req.getParameter("id");
-      if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
-      // Hier code zum Loeschen
+
+      if (idParam == null)
+        throw new ServletModuleException("Invalid call to delete: no id supplied");
+
       String confirmParam = req.getParameter("confirm");
       String cancelParam = req.getParameter("cancel");
       if (confirmParam == null && cancelParam == null) {
-        // HTML Ausgabe zum Confirmen!
         SimpleHash mergeData = new SimpleHash();
-        String moduleClassName = mainModule.getClass().getName();
-        int i = moduleClassName.indexOf(".Module");
-        String moduleName = moduleClassName.substring(i+7);
-        mergeData.put("module", moduleName);
-        mergeData.put("infoString", moduleName + ": " + idParam);
+
+        mergeData.put("module", getOperationModuleName());
+        mergeData.put("infoString", getOperationModuleName() + ": " + idParam);
         mergeData.put("id", idParam);
         mergeData.put("where", req.getParameter("where"));
         mergeData.put("order", req.getParameter("order"));
         mergeData.put("offset", req.getParameter("offset"));
-        deliver(req, res, mergeData,templateConfirmString);
-      } else {
-        if (confirmParam!= null && !confirmParam.equals("")) {
+        deliver(req, res, mergeData, templateConfirmString);
+      }
+      else {
+        if (confirmParam != null && !confirmParam.equals("")) {
           //theLog.printInfo("delete confirmed!");
           mainModule.deleteById(idParam);
-          list(req,res); // back to list
-        } else {
+          list(req, res); // back to list
+        }
+        else {
           if (req.getParameter("where") != null)
-              list(req,res);
+            list(req, res);
           else
-            edit(req,res);
+            edit(req, res);
         }
       }
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
+    }
+    catch (Exception e) {
+      throw new ServletModuleException(e.getMessage());
     }
   }
 
@@ -195,16 +263,17 @@ public abstract class ServletModule {
    * @param res Http-Response, die vom Dispatcher durchgereicht wird
    */
   public void edit(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException {
+      throws ServletModuleException {
     try {
       String idParam = req.getParameter("id");
       deliver(req, res, mainModule.getById(idParam), templateObjektString);
-    } catch(ModuleException e) {
-      throw new ServletModuleException(e.toString());
+    }
+    catch (ModuleException e) {
+      throw new ServletModuleException(e.getMessage());
     }
   }
 
-/**
+  /**
    *  update(req,res) - generische Updatemethode. Wennn die Funktionalitaet
    *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
    *  ueberschreiben werden.
@@ -214,42 +283,26 @@ public abstract class ServletModule {
    */
 
   public void update(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException {
+      throws ServletModuleException {
     try {
       String idParam = req.getParameter("id");
       HashMap withValues = getIntersectingValues(req, mainModule.getStorageObject());
+
       String id = mainModule.set(withValues);
-      //theLog.printInfo("Showing Entity with id: " + id);
-      //edit(req,res);
       String whereParam = req.getParameter("where");
       String orderParam = req.getParameter("order");
-      if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){
-        //theLog.printDebugInfo("update to list");
-        list(req,res);
-      } else {
+
+      if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) {
+        list(req, res);
+      }
+      else {
         edit(req, res);
       }
-      //list(req,res);
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
     }
-  }
-
-  // Hilfsprozeduren
-  /**
-  public void predeliver(HttpServletResponse res, TemplateModelRoot rtm, String tmpl)
-    throws ServletModuleException {
-    try {
-      PrintWriter out = new LineFilterWriter(res.getWriter());
-      StringWriter a = new StringWriter();
-      deliver(new PrintWriter(a),rtm,tmpl);
-      out.write(a.toString());
-      out.flush();
-    } catch (Exception e) {
-      e.printStackTrace();System.err.println(e.toString());
+    catch (Exception e) {
+      throw new ServletModuleException(e.getMessage());
     }
   }
-  */
 
   /**
    * deliver liefert das Template mit dem Filenamen templateFilename
@@ -262,34 +315,75 @@ public abstract class ServletModule {
    * @param tmpl Name des Templates
    * @exception ServletModuleException
    */
-  public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, String templateFilename)
-    throws ServletModuleException {
+  public void deliver(HttpServletRequest req, HttpServletResponse res,
+                      TemplateModelRoot rtm, TemplateModelRoot popups,
+                      String templateFilename)
+      throws ServletModuleException {
     if (rtm == null) rtm = new SimpleHash();
     try {
-      //PrintWriter out =  new LineFilterWriter(res.getWriter());
-      PrintWriter out =  res.getWriter();
-      HTMLTemplateProcessor.process(res,getLanguage(req)+"/"+templateFilename, rtm , out);
+      PrintWriter out = res.getWriter();
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req));
+
+      // we default to admin bundles here, which is not exactly beautiful...
+      // but this whole producer stuff is going to be rewritten soon.
+      // ServletModuleOpenIndy overwrites deliver() to use open bundles
+      // (br1)
       out.close();
-    } catch (HTMLParseException e) {
-      throw new ServletModuleException(e.toString());
+    }
+    catch (HTMLParseException e) {
+      throw new ServletModuleException(e.getMessage());
     } catch (IOException e) {
-      throw new ServletModuleException(e.toString());
+      throw new ServletModuleException(e.getMessage());
     }
   }
+
+
+  /**
+   * deliver liefert das Template mit dem Filenamen templateFilename
+   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
+   * TemplateModelRoot rtm gemischt wurde
+   *
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
+   * @param tmpl Name des Templates
+   * @exception ServletModuleException
+   */
+  public void deliver(HttpServletRequest req, HttpServletResponse res,
+                      TemplateModelRoot rtm, String templateFilename)
+      throws ServletModuleException {
+    deliver(req, res, rtm, null, templateFilename);
+  }
+
   /**
    * deliver liefert das Template mit dem Filenamen templateFilename
    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
    * TemplateModelRoot rtm gemischt wurde
    *
    * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   * @param entity Entity, aus der die Daten, die ins Template gemerged werden sollen.
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
    * @param tmpl Name des Templates
    * @exception ServletModuleException
    */
-  public void deliver(HttpServletRequest req, HttpServletResponse res, Entity ent, String templateFilename)
-    throws ServletModuleException {
-    deliver(req, res,HTMLTemplateProcessor.makeSimpleHash(ent), templateFilename);
+  public void deliver_compressed(HttpServletRequest req, HttpServletResponse res,
+                                 TemplateModelRoot rtm, String templateFilename)
+      throws ServletModuleException {
+    if (rtm == null) rtm = new SimpleHash();
+    try {
+      PrintWriter out = new LineFilterWriter(res.getWriter());
+      //PrintWriter out =  res.getWriter();
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));
+      out.close();
+    }
+    catch (HTMLParseException e) {
+      throw new ServletModuleException(e.getMessage());
+    }
+    catch (IOException e) {
+      throw new ServletModuleException(e.getMessage());
+    }
   }
+
   /**
    * deliver liefert das Template mit dem Filenamen templateFilename
    * an den HttpServletResponse res aus, nachdem es mit den Daten aus
@@ -301,9 +395,10 @@ public abstract class ServletModule {
    * @param tmpl Name des Templates
    * @exception ServletModuleException
    */
-  private void deliver(HttpServletResponse res,HttpServletRequest req, PrintWriter out, TemplateModelRoot rtm, String templateFilename)
-    throws HTMLParseException {
-    HTMLTemplateProcessor.process(res,getLanguage(req)+"/"+templateFilename, rtm , out);
+  private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out,
+                       TemplateModelRoot rtm, String templateFilename)
+      throws HTMLParseException {
+    HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));
   }
 
   /**
@@ -313,14 +408,18 @@ public abstract class ServletModule {
    *
    * @return Name der Default-Action
    */
-  public String defaultAction() { return defaultAction; }
+  public String defaultAction() {
+    return defaultAction;
+  }
 
-    /**
+  /**
    *  Hier kann vor der Datenaufbereitung schon mal ein response geschickt
    *  werden (um das subjektive Antwortverhalten bei langsamen Verbindungen
    *  zu verbessern).
    */
-  public void predeliver(HttpServletRequest req, HttpServletResponse res) { ; }
+  public void predeliver(HttpServletRequest req, HttpServletResponse res) {
+    ;
+  }
 
   /**
    * Holt die Felder aus der Metadatenfelderliste des StorageObjects, die
@@ -329,21 +428,22 @@ public abstract class ServletModule {
    * @return HashMap mit den Werten
    */
   public HashMap getIntersectingValues(HttpServletRequest req, StorageObject theStorage)
-    throws ServletModuleException {
+      throws ServletModuleException {
     ArrayList theFieldList;
     try {
-        theFieldList = theStorage.getFields();
-    } catch (StorageObjectException e) {
-      throw new ServletModuleException("ServletModule.getIntersectingValues: " + e.toString());
+      theFieldList = theStorage.getFields();
+    }
+    catch (StorageObjectException e) {
+      throw new ServletModuleException("ServletModule.getIntersectingValues: " + e.getMessage());
     }
 
     HashMap withValues = new HashMap();
     String aField, aValue;
 
-    for(int i=0; i<theFieldList.size();i++) {
-      aField = (String)theFieldList.get(i);
+    for (int i = 0; i < theFieldList.size(); i++) {
+      aField = (String) theFieldList.get(i);
       aValue = req.getParameter(aField);
-      if (aValue!=null) withValues.put(aField,aValue);
+      if (aValue != null) withValues.put(aField, aValue);
     }
     return withValues;
   }