scripts/mir-setup/README: update with link to new doc on wiki
[mir.git] / source / Mir.java
index 263c4cd..011b1f9 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-import java.io.IOException;\r
-import java.io.PrintWriter;\r
-import java.lang.reflect.Method;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Locale;\r
-import java.util.*;\r
-\r
-import javax.servlet.ServletException;\r
-import javax.servlet.UnavailableException;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import freemarker.template.*;\r
-\r
-import org.apache.struts.util.MessageResources;\r
-\r
-import mir.misc.*;\r
-import mir.servlet.*;\r
-import mir.util.*;\r
-import mir.generator.*;\r
-//import mir.log.Log;\r
-\r
-import mircoders.global.*;\r
-import mircoders.localizer.*;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.module.ModuleMessage;\r
-import mircoders.module.ModuleUsers;\r
-import mircoders.storage.DatabaseArticleType;\r
-import mircoders.storage.DatabaseMessages;\r
-import mircoders.storage.DatabaseUsers;\r
-\r
-/**\r
- * Mir.java - main servlet, that dispatches to servletmodules\r
- *\r
- * @author $Author: mh $\r
- * @version $Id: Mir.java,v 1.25 2002/12/23 03:00:11 mh Exp $\r
- *\r
- */\r
-\r
-public class Mir extends AbstractServlet {\r
-\r
-  private static ModuleUsers usersModule = null;\r
-  private static ModuleMessage messageModule = null;\r
-  private final static HashMap servletModuleInstanceHash = new HashMap();\r
-\r
-  private static List loginLanguages = null;\r
-\r
-  public HttpSession session;\r
-\r
-  public void doGet(HttpServletRequest req, HttpServletResponse res) throws\r
-      ServletException, IOException {\r
-    doPost(req, res);\r
-  }\r
-\r
-  protected TemplateModel getLoginLanguages() throws ServletException {\r
-    synchronized (Mir.class) {\r
-      try {\r
-\r
-        if (loginLanguages == null) {\r
-          MessageResources messageResources2 = MessageResources.\r
-              getMessageResources("bundles.admin");\r
-          MessageResources messageResources = MessageResources.\r
-              getMessageResources("bundles.adminlocal");\r
-          List languages = StringRoutines.splitString(MirGlobal.\r
-              getConfigPropertyWithDefault("Mir.Login.Languages", "en"), ";");\r
-\r
-          loginLanguages = new Vector();\r
-          Iterator i = languages.iterator();\r
-\r
-          while (i.hasNext()) {\r
-            String code = (String) i.next();\r
-            Locale locale = new Locale(code, "");\r
-            String name = messageResources.getMessage(locale, "languagename");\r
-            if (name == null)\r
-              name = messageResources2.getMessage(locale, "languagename");\r
-            if (name == null)\r
-              name = code;\r
-\r
-            Map record = new HashMap();\r
-            record.put("name", name);\r
-            record.put("code", code);\r
-            loginLanguages.add(record);\r
-          }\r
-        }\r
-\r
-        return FreemarkerGenerator.makeAdapter(loginLanguages);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletException(t.getMessage());\r
-      }\r
-    }\r
-  }\r
-\r
-  public void doPost(HttpServletRequest req, HttpServletResponse res) throws\r
-      ServletException, IOException, UnavailableException {\r
-\r
-    long startTime = System.currentTimeMillis();\r
-    long sessionConnectTime = 0;\r
-    EntityUsers userEntity;\r
-    String http = "";\r
-\r
-    if (getServletContext().getAttribute("mir.confed") == null) {\r
-      getConfig(req);\r
-    }\r
-\r
-    MirConfig.setServletName(getServletName());\r
-\r
-    //*** test\r
-     // Log.info(this, "blalalala");\r
-\r
-    session = req.getSession(true);\r
-    userEntity = (EntityUsers) session.getAttribute("login.uid");\r
-\r
-    if (req.getServerPort() == 443)\r
-      http = "https";\r
-    else\r
-      http = "http";\r
-\r
-\r
-    //make sure client browsers don't cache anything\r
-    setNoCaching(res);\r
-\r
-    res.setContentType("text/html; charset=" + MirConfig.getProp("Mir.DefaultHTMLCharset"));\r
-\r
-    String moduleName = req.getParameter("module");\r
-    checkLanguage(session, req);\r
-\r
-    /** @todo for cleanup and readability this should be moved to\r
-     *  method loginIfNecessary() */\r
-\r
-    if (moduleName != null && moduleName.equals("direct")) {\r
-      //...\r
-    }\r
-\r
-    // Authentication\r
-    if ( (moduleName != null && moduleName.equals("login")) || (userEntity == null)) {\r
-      String user = req.getParameter("login");\r
-      String passwd = req.getParameter("password");\r
-      theLog.printDebugInfo("--login: evaluating for user: " + user);\r
-      userEntity = allowedUser(user, passwd);\r
-      if (userEntity == null) {\r
-        // login failed: redirecting to login\r
-        theLog.printWarning("--login: failed!");\r
-        _sendLoginPage(res, req, res.getWriter());\r
-        return;\r
-      }\r
-      else if (moduleName != null && moduleName.equals("login")) {\r
-        // login successful\r
-\r
-        theLog.printInfo("--login: successful! setting uid: " +\r
-                         userEntity.getId());\r
-        session.setAttribute("login.uid", userEntity);\r
-        theLog.printDebugInfo("--login: trying to retrieve login.target");\r
-        String target = (String) session.getAttribute("login.target");\r
-\r
-        if (target != null) {\r
-          theLog.printDebugInfo("Redirect: " + target);\r
-          int serverPort = req.getServerPort();\r
-          String redirect = "";\r
-          String redirectString = "";\r
-\r
-          if (serverPort == 80) {\r
-            redirect = res.encodeURL(http + "://" + req.getServerName() +\r
-                                     target);\r
-            redirectString =\r
-                "<html><head><meta http-equiv=refresh content=\"1;URL="\r
-                + redirect\r
-                + "\"></head><body>going <a href=\"" + redirect +\r
-                "\">Mir</a></body></html>";\r
-          }\r
-          else {\r
-            redirect = res.encodeURL(http + "://" + req.getServerName() + ":" +\r
-                                     req.getServerPort() + target);\r
-            redirectString =\r
-                "<html><head><meta http-equiv=refresh content=\"1;URL="\r
-                + redirect\r
-                + "\"></head><body>going <a href=\"" + redirect +\r
-                "\">Mir</a></body></html>";\r
-          }\r
-          res.getWriter().println(redirectString);\r
-\r
-          //res.sendRedirect(redirect);\r
-\r
-        }\r
-        else {\r
-          // redirecting to default target\r
-          theLog.printDebugInfo("--login: no target - redirecting to default");\r
-          _sendStartPage(res, req, res.getWriter(), userEntity);\r
-        }\r
-        return;\r
-      } // if login succesful\r
-    } // if login\r
-\r
-    if (moduleName != null && moduleName.equals("logout")) {\r
-      theLog.printDebugInfo("--logout");\r
-      session.invalidate();\r
-\r
-      //session = req.getSession(true);\r
-      //checkLanguage(session, req);\r
-      _sendLoginPage(res, req, res.getWriter());\r
-      return;\r
-    }\r
-\r
-    // Check if authed!\r
-    if (userEntity == null) {\r
-      // redirect to loginpage\r
-      String redirectString = req.getRequestURI();\r
-      String queryString = req.getQueryString();\r
-      if (queryString != null && !queryString.equals("")) {\r
-        redirectString += "?" + req.getQueryString();\r
-        theLog.printDebugInfo("STORING: " + redirectString);\r
-        session.setAttribute("login.target", redirectString);\r
-      }\r
-      _sendLoginPage(res, req, res.getWriter());\r
-      return;\r
-    }\r
-\r
-    // If no module is specified goto standard startpage\r
-    if (moduleName == null || moduleName.equals("")) {\r
-      theLog.printDebugInfo("no module: redirect to standardpage");\r
-      _sendStartPage(res, req, res.getWriter(), userEntity);\r
-      return;\r
-    }\r
-    // end of auth\r
-\r
-    // From now on regular dispatching...\r
-    try {\r
-      // get servletmodule by parameter and continue with dispacher\r
-      ServletModule smod = getServletModuleForName(moduleName);\r
-      ServletModuleDispatch.dispatch(smod, req, res);\r
-    }\r
-    catch (ServletModuleException e) {\r
-      handleError(req, res, res.getWriter(),\r
-                  "ServletException in Module " + moduleName + " -- " +\r
-                  e.getMessage());\r
-    }\r
-    catch (ServletModuleUserException e) {\r
-      handleUserError(req, res, res.getWriter(), e.getMessage());\r
-    }\r
-\r
-    // timing...\r
-    sessionConnectTime = System.currentTimeMillis() - startTime;\r
-    theLog.printInfo("EXECTIME (" + moduleName + "): " + sessionConnectTime +\r
-                     " ms");\r
-  }\r
-\r
-  /**\r
-   *  Private method getServletModuleForName returns ServletModule\r
-   *  from Cache\r
-   *\r
-   * @param moduleName\r
-   * @return ServletModule\r
-   *\r
-   */\r
-  private static ServletModule getServletModuleForName(String moduleName) throws\r
-      ServletModuleException {\r
-\r
-    // Instance in Map ?\r
-    if (!servletModuleInstanceHash.containsKey(moduleName)) {\r
-      // was not found in hash...\r
-      try {\r
-        Class theServletModuleClass = null;\r
-        try {\r
-          // first we try to get ServletModule from stern.che3.servlet\r
-          theServletModuleClass = Class.forName(\r
-              "mircoders.servlet.ServletModule" + moduleName);\r
-        }\r
-        catch (ClassNotFoundException e) {\r
-          // on failure, we try to get it from lib-layer\r
-          theServletModuleClass = Class.forName("mir.servlet.ServletModule" +\r
-                                                moduleName);\r
-        }\r
-        Method m = theServletModuleClass.getMethod("getInstance", null);\r
-        ServletModule smod = (ServletModule) m.invoke(null, null);\r
-        // we put it into map for further reference\r
-        servletModuleInstanceHash.put(moduleName, smod);\r
-        return smod;\r
-      }\r
-      catch (Exception e) {\r
-        throw new ServletModuleException("*** error resolving classname for " +\r
-                                         moduleName + " -- " + e.getMessage());\r
-      }\r
-    }\r
-    else\r
-      return (ServletModule) servletModuleInstanceHash.get(moduleName);\r
-  }\r
-\r
-  private void handleError(HttpServletRequest req, HttpServletResponse res,\r
-                           PrintWriter out, String errorString) {\r
-\r
-    try {\r
-      theLog.printError(errorString);\r
-      SimpleHash modelRoot = new SimpleHash();\r
-      modelRoot.put("errorstring", new SimpleScalar(errorString));\r
-      modelRoot.put("date",\r
-                    new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));\r
-      HTMLTemplateProcessor.process(res, MirConfig.getProp("Mir.ErrorTemplate"),\r
-                                    modelRoot, out, getLocale(req));\r
-      out.close();\r
-    }\r
-    catch (Exception e) {\r
-      e.printStackTrace(System.out);\r
-      System.err.println("Error in ErrorTemplate: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  private void handleUserError(HttpServletRequest req, HttpServletResponse res,\r
-                               PrintWriter out, String errorString) {\r
-    try {\r
-      theLog.printError(errorString);\r
-      SimpleHash modelRoot = new SimpleHash();\r
-      modelRoot.put("errorstring", new SimpleScalar(errorString));\r
-      modelRoot.put("date",\r
-                    new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));\r
-      HTMLTemplateProcessor.process(res,\r
-                                    MirConfig.getProp("Mir.UserErrorTemplate"),\r
-                                    modelRoot, out, getLocale(req));\r
-      out.close();\r
-    }\r
-    catch (Exception e) {\r
-      System.err.println("Error in UserErrorTemplate");\r
-    }\r
-\r
-  }\r
-\r
-  /**\r
-   *  evaluate login for user / password\r
-   */\r
-  protected EntityUsers allowedUser(String user, String password) {\r
-    try {\r
-      if (usersModule == null)\r
-        usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
-      return usersModule.getUserForLogin(user, password);\r
-    }\r
-    catch (Exception e) {\r
-      theLog.printDebugInfo(e.getMessage());\r
-      e.printStackTrace();\r
-      return null;\r
-    }\r
-  }\r
-\r
-  // Redirect-methods\r
-  private void _sendLoginPage(HttpServletResponse res, HttpServletRequest req,\r
-                              PrintWriter out) {\r
-    String loginTemplate = MirConfig.getProp("Mir.LoginTemplate");\r
-    String sessionUrl = res.encodeURL("");\r
-\r
-    try {\r
-      SimpleHash mergeData = new SimpleHash();\r
-      SimpleList languages = new SimpleList();\r
-\r
-      mergeData.put("session", sessionUrl);\r
-\r
-      String defaultlanguage = MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", "");\r
-      if (defaultlanguage.length() == 0)\r
-        defaultlanguage = req.getLocale().getLanguage();\r
-      mergeData.put("defaultlanguage",  defaultlanguage);\r
-      mergeData.put("languages", getLoginLanguages());\r
-\r
-      HTMLTemplateProcessor.process(res, loginTemplate, mergeData, out, getLocale(req));\r
-    }\r
-    catch (Throwable e) {\r
-      handleError(req, res, out, "Error sending login page: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  private void _sendStartPage(HttpServletResponse res, HttpServletRequest req,\r
-                              PrintWriter out, EntityUsers userEntity) {\r
-    String startTemplate = "templates/admin/start_admin.template";\r
-    String sessionUrl = res.encodeURL("");\r
-\r
-    try {\r
-      // merge with logged in user and messages\r
-      SimpleHash mergeData = new SimpleHash();\r
-      mergeData.put("session", sessionUrl);\r
-      mergeData.put("login_user", userEntity);\r
-      if (messageModule == null)\r
-        messageModule = new ModuleMessage(DatabaseMessages.getInstance());\r
-      mergeData.put("messages",\r
-                    messageModule.getByWhereClause(null, "webdb_create desc", 0,\r
-          10));\r
-\r
-      mergeData.put("articletypes",\r
-                    DatabaseArticleType.getInstance().\r
-                    selectByWhereClause("", "id", 0, 20));\r
-\r
-      HTMLTemplateProcessor.process(res, startTemplate, mergeData, out, getLocale(req));\r
-    }\r
-    catch (Exception e) {\r
-      e.printStackTrace(System.out);\r
-      handleError(req, res, out, "error while trying to send startpage. " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public String getServletInfo() {\r
-    return "Mir " + MirConfig.getProp("Mir.Version");\r
-  }\r
-\r
-  private void checkLanguage(HttpSession session, HttpServletRequest req) {\r
-    // a lang parameter always sets the language\r
-    String lang = req.getParameter("language");\r
-    if (lang != null) {\r
-      theLog.printInfo("selected language " + lang + " overrides accept-language");\r
-      setLanguage(session, lang);\r
-      setLocale(session, new Locale(lang, ""));\r
-    }\r
-    // otherwise store language from accept header in session\r
-    else if (session.getAttribute("Language") == null) {\r
-      theLog.printInfo("accept-language is " + req.getLocale().getLanguage());\r
-      setLanguage(session, req.getLocale().getLanguage());\r
-      setLocale(session, req.getLocale());\r
-    }\r
-  }\r
-}\r
+/*
+ * Copyright (C) 2001-2006 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  any library licensed under the Apache Software License,
+ * 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.
+ */
+
+import mir.bundle.Bundle;
+import mir.config.MirPropertiesConfiguration;
+import mir.servlet.AbstractServlet;
+import mir.servlet.AdminServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.ExceptionRoutines;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleUsers;
+import mircoders.servlet.ServletHelper;
+import multex.Failure;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.UnavailableException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+public class Mir extends AbstractServlet {
+  private static ModuleUsers usersModule = null;
+  private static Locale fallbackLocale = null;
+
+  private static List loginLanguages = null;
+
+  private List getLoginLanguages() throws Failure {
+    synchronized (Mir.class) {
+      try {
+        if (loginLanguages == null) {
+          List languages =
+            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
+
+          loginLanguages = new ArrayList();
+
+          Iterator i = languages.iterator();
+
+          while (i.hasNext()) {
+            String code = (String) i.next();
+
+            Bundle bundle =
+                MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new String[] { code });
+            Bundle defaultBundle =
+                MirGlobal.getBundleFactory().getBundle("bundles/admin", new String[] { code });
+
+            String name = bundle.getValue("languagename", Collections.EMPTY_LIST);
+
+            if (name == null) {
+              name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST);
+            }
+
+            if (name == null) {
+              name = code;
+            }
+
+            Map record = new HashMap();
+            record.put("name", name);
+            record.put("code", code);
+            loginLanguages.add(record);
+          }
+        }
+
+        return loginLanguages;
+      }
+      catch (Throwable t) {
+        throw new Failure("Error while retrieving the available login languages", t);
+      }
+    }
+  }
+
+  public void init(ServletConfig config) throws ServletException {
+    super.init(config);
+
+    usersModule = new ModuleUsers();
+  }
+
+  protected String getDefaultLanguage(HttpServletRequest aRequest) {
+    String defaultlanguage =
+      MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
+
+    if (defaultlanguage.length() == 0) {
+      Locale locale = aRequest.getLocale();
+      defaultlanguage = locale.getLanguage();
+    }
+
+    return defaultlanguage;
+  }
+
+  protected synchronized Locale getFallbackLocale() throws ServletException {
+    try {
+      if (fallbackLocale == null) {
+        fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletException(t.getMessage());
+    }
+
+    return fallbackLocale;
+  }
+
+  public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {
+    try {
+      EntityUsers user = ServletHelper.getUser(aRequest);
+
+      String username = aRequest.getParameter("login");
+      String password = aRequest.getParameter("password");
+
+      if (username != null && password != null) {
+        user = usersModule.getUserForLogin(username, password);
+
+        if (user!=null) {
+          ServletHelper.setUser(aRequest, user);
+          usersModule.recordLogin(user);
+          aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId()));
+        }
+      }
+
+      return user;
+    }
+    catch (Throwable t) {
+      throw new ServletException(t.getMessage());
+    }
+  }
+
+  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {
+    try {
+      long startTime = System.currentTimeMillis();
+      long sessionConnectTime = 0;
+
+      HttpSession session = aRequest.getSession(true);
+      setNoCaching(aResponse);
+      aResponse.setContentType("text/html; charset=" +
+                               configuration.
+                               getString("Mir.DefaultHTMLCharset", "UTF-8"));
+
+      EntityUsers userEntity = checkCredentials(aRequest);
+
+      if (userEntity == null) {
+        String queryString = aRequest.getQueryString();
+
+        if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&
+             (aRequest.getParameter("module")==null ||
+              (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {
+          session.setAttribute("login.target", queryString);
+        }
+
+        _sendLoginPage(aResponse, aRequest);
+      }
+      else {
+        String moduleName = aRequest.getParameter("module");
+        checkLanguage(session, aRequest);
+
+        if ( ( (moduleName == null) || moduleName.equals(""))) {
+          moduleName="Admin";
+        }
+
+        if (moduleName.equals("login")) {
+          String target = (String) session.getAttribute("login.target");
+
+          if (target != null) {
+            ServletHelper.redirect(aResponse, target);
+          }
+          else {
+            ServletHelper.redirect(aResponse, "");
+          }
+        }
+        else if (moduleName.equals("logout")) {
+          logger.info(userEntity.getFieldValue("login") + " has logged out");
+          session.invalidate();
+          _sendLoginPage(aResponse, aRequest);
+          return;
+        }
+        else {
+          try {
+            AdminServletModule servletModule = getServletModuleForName(moduleName);
+            servletModule.handleRequest(aRequest, aResponse);
+
+            sessionConnectTime = System.currentTimeMillis() - startTime;
+            logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
+          }
+          catch (Throwable e) {
+            Throwable cause = ExceptionRoutines.traceCauseException(e);
+
+            if (cause instanceof ServletModuleUserExc)
+              handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
+            else
+              handleError(aRequest, aResponse, cause);
+          }
+
+          if (aRequest.getParameter("killsession")!=null)
+            aRequest.getSession().invalidate();
+        }
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletException(t.toString());
+    }
+  }
+
+  /**
+   * caching routine to get a module for a module name
+   *
+   * @param aModuleName the module name
+   * @return the requested module
+   * @throws ServletModuleExc
+   */
+  private static AdminServletModule getServletModuleForName(String aModuleName) throws ServletModuleExc {
+    return ServletHelper.getServletModule(aModuleName);
+  }
+
+  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
+    try {
+      logger.info("user error: " + anException.getMessage());
+
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      Bundle bundle =
+          MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new
+              String[] { getLocale(aRequest).getLanguage() });
+      Bundle defaultBundle =
+          MirGlobal.getBundleFactory().getBundle("bundles/admin", new
+              String[] { getLocale(aRequest).getLanguage() });
+      String message =
+        bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
+
+      if (message==null) {
+        message =
+          defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
+      }
+
+      responseData.put("errorstring", message);
+      responseData.put("date", new GregorianCalendar().getTime());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));
+    }
+    catch (Throwable e) {
+      logger.error("Error handling user error" + e.toString());
+    }
+  }
+
+  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {
+    try {
+      logger.error("error: " + anException);
+
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      responseData.put("errorstring", anException.toString());
+      StringWriter writer = new StringWriter();
+      anException.printStackTrace(new PrintWriter(writer));
+      responseData.put("stacktrace", writer.toString());
+      responseData.put("date", new GregorianCalendar().getTime());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
+    }
+    catch (Throwable e) {
+      logger.error("Error handling error: " + e.toString());
+
+      try {
+        Throwable rootException = ExceptionRoutines.traceCauseException(anException);
+
+        PrintWriter writer = aResponse.getWriter();
+        writer.println("<html><head><title>FATAL Error</title><body>");
+        writer.println("<h1>" + rootException.toString()+"</h1>");
+        writer.println("<code>");
+        rootException.printStackTrace(writer);
+        writer.println("</code>");
+        writer.println("</body></html>");
+        writer.close();
+      }
+      catch (Throwable t) {
+
+      }
+    }
+  }
+
+  // Redirect-methods
+  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {
+    String loginTemplate = configuration.getString("Mir.LoginTemplate");
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      responseData.put("defaultlanguage", getDefaultLanguage(aRequest));
+      responseData.put("languages", getLoginLanguages());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);
+    }
+    catch (Throwable e) {
+      handleError(aRequest, aResponse, e);
+    }
+  }
+
+  public String getServletInfo() {
+    return "Mir " + configuration.getString("Mir.Version");
+  }
+
+  private class SessionTracker implements HttpSessionBindingListener {
+    private String name;
+    private String id;
+
+    public SessionTracker(String aUserName, String anId) {
+      name = aUserName;
+      id = anId;
+    }
+
+    public void valueBound(HttpSessionBindingEvent anEvent) {
+      MirGlobal.registerLogin(name, id);
+    }
+
+    public void valueUnbound(HttpSessionBindingEvent anEvent) {
+      MirGlobal.registerLogout(name, id);
+    }
+  }
+}