for some unexplainable reason, Mir.java was empty after my work from last
authorzapata <zapata>
Fri, 7 Mar 2003 00:50:22 +0000 (00:50 +0000)
committerzapata <zapata>
Fri, 7 Mar 2003 00:50:22 +0000 (00:50 +0000)
night...

source/Mir.java
source/OpenMir.java

index e69de29..31650ea 100755 (executable)
@@ -0,0 +1,489 @@
+/*\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.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import java.util.Vector;\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 mir.config.MirPropertiesConfiguration;\r
+import mir.generator.FreemarkerGenerator;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.HTMLTemplateProcessor;\r
+import mir.misc.StringUtil;\r
+import mir.servlet.AbstractServlet;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleDispatch;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.util.StringRoutines;\r
+import mir.util.ExceptionFunctions;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\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
+import org.apache.struts.util.MessageResources;\r
+\r
+import freemarker.template.SimpleHash;\r
+import freemarker.template.SimpleList;\r
+import freemarker.template.SimpleScalar;\r
+import freemarker.template.TemplateModel;\r
+\r
+\r
+\r
+/**\r
+ * Mir.java - main servlet, that dispatches to servletmodules\r
+ *\r
+ * @author $Author: zapata $\r
+ * @version $Id: Mir.java,v 1.34 2003/03/07 00:50:22 zapata Exp $\r
+ *\r
+ */\r
+public class Mir extends AbstractServlet {\r
+  private static ModuleUsers usersModule = null;\r
+  private static ModuleMessage messageModule = null;\r
+  private final static Map servletModuleInstanceHash = new HashMap();\r
+\r
+  //I don't know about making this static cause it removes the\r
+  //possibility to change the config on the fly.. -mh\r
+  private static List loginLanguages = null;\r
+  public HttpSession session;\r
+\r
+  public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+    throws ServletException, IOException {\r
+    doPost(aRequest, aResponse);\r
+  }\r
+\r
+  protected TemplateModel getLoginLanguages() throws ServletException {\r
+    synchronized (Mir.class) {\r
+      try {\r
+        if (loginLanguages == null) {\r
+          MessageResources messageResources2 =\r
+            MessageResources.getMessageResources("bundles.admin");\r
+          MessageResources messageResources =\r
+            MessageResources.getMessageResources("bundles.adminlocal");\r
+          List languages =\r
+            StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault(\r
+                "Mir.Login.Languages", "en"), ";");\r
+\r
+          loginLanguages = new Vector();\r
+\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
+\r
+            if (name == null) {\r
+              name = messageResources2.getMessage(locale, "languagename");\r
+            }\r
+\r
+            if (name == null) {\r
+              name = code;\r
+            }\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
+  // FIXME: this should probalby go into AbstractServlet so it can be used in\r
+  // OpenMir as well -mh\r
+  protected String getDefaultLanguage(HttpServletRequest aRequest) {\r
+    String defaultlanguage =\r
+      MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", "");\r
+\r
+    if (defaultlanguage.length() == 0) {\r
+      Locale locale = aRequest.getLocale();\r
+      defaultlanguage = locale.getLanguage();\r
+    }\r
+\r
+    return defaultlanguage;\r
+  }\r
+\r
+  public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+    throws ServletException, IOException, UnavailableException {\r
+    long startTime = System.currentTimeMillis();\r
+    long sessionConnectTime = 0;\r
+    EntityUsers userEntity;\r
+    String http = "";\r
+\r
+    if ((configuration.getString("RootUri") == null) ||\r
+        configuration.getString("RootUri").equals("")) {\r
+      configuration.setProperty("RootUri", aRequest.getContextPath());\r
+    }\r
+\r
+    configuration.addProperty("ServletName", getServletName());\r
+\r
+    //*** test\r
+    // Log.info(this, "blalalala");\r
+    session = aRequest.getSession(true);\r
+    userEntity = (EntityUsers) session.getAttribute("login.uid");\r
+\r
+    if (aRequest.getServerPort() == 443) {\r
+      http = "https";\r
+    } else {\r
+      http = "http";\r
+    }\r
+\r
+    //make sure client browsers don't cache anything\r
+    setNoCaching(aResponse);\r
+\r
+    //FIXME: this seems kind of hackish and only here because we can have\r
+    // default other than the one that the browser is set to.\r
+    Locale locale = new Locale(getDefaultLanguage(aRequest), "");\r
+    MessageResources messageResources =\r
+      MessageResources.getMessageResources("bundles.admin");\r
+    String htmlcharset = messageResources.getMessage(locale, "htmlcharset");\r
+\r
+    aResponse.setContentType("text/html; charset=" + htmlcharset);\r
+\r
+    String moduleName = aRequest.getParameter("module");\r
+    checkLanguage(session, aRequest);\r
+\r
+    /** @todo for cleanup and readability this should be moved to\r
+     *  method loginIfNecessary() */\r
+    if ((moduleName != null) && moduleName.equals("direct")) {\r
+      //...\r
+    }\r
+\r
+    // Authentication\r
+    if (((moduleName != null) && moduleName.equals("login")) ||\r
+        (userEntity == null)) {\r
+      String user = aRequest.getParameter("login");\r
+      String passwd = aRequest.getParameter("password");\r
+      logger.debug("--login: evaluating for user: " + user);\r
+      userEntity = allowedUser(user, passwd);\r
+\r
+      if (userEntity == null) {\r
+        // login failed: redirecting to login\r
+        logger.warn("--login: failed!");\r
+        _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
+\r
+        return;\r
+      } else if ((moduleName != null) && moduleName.equals("login")) {\r
+        // login successful\r
+        logger.info("--login: successful! setting uid: " + userEntity.getId());\r
+        session.setAttribute("login.uid", userEntity);\r
+        logger.debug("--login: trying to retrieve login.target");\r
+\r
+        String target = (String) session.getAttribute("login.target");\r
+\r
+        if (target != null) {\r
+          logger.debug("Redirect: " + target);\r
+\r
+          int serverPort = aRequest.getServerPort();\r
+          String redirect = "";\r
+          String redirectString = "";\r
+\r
+          if (serverPort == 80) {\r
+            redirect =\r
+              aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);\r
+            redirectString =\r
+              "<html><head><meta http-equiv=refresh content=\"1;URL=" +\r
+              redirect + "\"></head><body>going <a href=\"" + redirect +\r
+              "\">Mir</a></body></html>";\r
+          } else {\r
+            redirect =\r
+              aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +\r
+                aRequest.getServerPort() + target);\r
+            redirectString =\r
+              "<html><head><meta http-equiv=refresh content=\"1;URL=" +\r
+              redirect + "\"></head><body>going <a href=\"" + redirect +\r
+              "\">Mir</a></body></html>";\r
+          }\r
+\r
+          aResponse.getWriter().println(redirectString);\r
+\r
+          //aResponse.sendRedirect(redirect);\r
+        } else {\r
+          // redirecting to default target\r
+          logger.debug("--login: no target - redirecting to default");\r
+          _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);\r
+        }\r
+\r
+        return;\r
+      }\r
+       // if login succesful\r
+    }\r
+     // if login\r
+\r
+    if ((moduleName != null) && moduleName.equals("logout")) {\r
+      logger.info("--logout");\r
+      session.invalidate();\r
+\r
+      //session = aRequest.getSession(true);\r
+      //checkLanguage(session, aRequest);\r
+      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
+\r
+      return;\r
+    }\r
+\r
+    // Check if authed!\r
+    if (userEntity == null) {\r
+      // redirect to loginpage\r
+      String redirectString = aRequest.getRequestURI();\r
+      String queryString = aRequest.getQueryString();\r
+\r
+      if ((queryString != null) && !queryString.equals("")) {\r
+        redirectString += ("?" + aRequest.getQueryString());\r
+        logger.debug("STORING: " + redirectString);\r
+        session.setAttribute("login.target", redirectString);\r
+      }\r
+\r
+      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
+\r
+      return;\r
+    }\r
+\r
+    // If no module is specified goto standard startpage\r
+    if ((moduleName == null) || moduleName.equals("")) {\r
+      logger.debug("no module: redirect to standardpage");\r
+      _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);\r
+\r
+      return;\r
+    }\r
+\r
+    // end of auth\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, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      Throwable cause = ExceptionFunctions.traceCauseException(e);\r
+\r
+      if (cause instanceof ServletModuleUserExc)\r
+        handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);\r
+      else\r
+        handleError(aRequest, aResponse, aResponse.getWriter(), cause);\r
+\r
+    }\r
+\r
+    // timing...\r
+    sessionConnectTime = System.currentTimeMillis() - startTime;\r
+    logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " 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 ServletModuleExc {\r
+    // Instance in Map ?\r
+    if (!servletModuleInstanceHash.containsKey(moduleName)) {\r
+      // was not found in hash...\r
+      try {\r
+        Class theServletModuleClass = null;\r
+\r
+        try {\r
+          // first we try to get ServletModule from stern.che3.servlet\r
+          theServletModuleClass =\r
+            Class.forName("mircoders.servlet.ServletModule" + moduleName);\r
+        } catch (ClassNotFoundException e) {\r
+          // on failure, we try to get it from lib-layer\r
+          theServletModuleClass =\r
+            Class.forName("mir.servlet.ServletModule" + moduleName);\r
+        }\r
+\r
+        Method m = theServletModuleClass.getMethod("getInstance", null);\r
+        ServletModule smod = (ServletModule) m.invoke(null, null);\r
+\r
+        // we put it into map for further reference\r
+        servletModuleInstanceHash.put(moduleName, smod);\r
+\r
+        return smod;\r
+      }\r
+      catch (Exception e) {\r
+        throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());\r
+      }\r
+    } else {\r
+      return (ServletModule) servletModuleInstanceHash.get(moduleName);\r
+    }\r
+  }\r
+\r
+  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+                               PrintWriter out, Throwable anException) {\r
+    try {\r
+      logger.info("user error: " + anException.getMessage());\r
+      SimpleHash modelRoot = new SimpleHash();\r
+      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));\r
+      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));\r
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),\r
+                                    modelRoot, out, aRequest.getLocale() );\r
+      out.close();\r
+    }\r
+    catch (Exception e) {\r
+      logger.error("Error in UserErrorTemplate");\r
+    }\r
+\r
+  }\r
+\r
+  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {\r
+\r
+    try {\r
+      logger.error("error: " + anException);\r
+      SimpleHash modelRoot = new SimpleHash();\r
+      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));\r
+      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(\r
+                                               new GregorianCalendar())));\r
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),\r
+                                    modelRoot,out, aRequest.getLocale());\r
+      out.close();\r
+    }\r
+    catch (Exception e) {\r
+      logger.error("Error in ErrorTemplate");\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
+      }\r
+\r
+      return usersModule.getUserForLogin(user, password);\r
+    } catch (Exception e) {\r
+      logger.debug(e.getMessage());\r
+      e.printStackTrace();\r
+\r
+      return null;\r
+    }\r
+  }\r
+\r
+  // Redirect-methods\r
+  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,\r
+    PrintWriter out) {\r
+    String loginTemplate = configuration.getString("Mir.LoginTemplate");\r
+    String sessionUrl = aResponse.encodeURL("");\r
+\r
+    try {\r
+      SimpleHash mergeData = new SimpleHash();\r
+      SimpleList languages = new SimpleList();\r
+\r
+      mergeData.put("session", sessionUrl);\r
+\r
+      mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));\r
+      mergeData.put("languages", getLoginLanguages());\r
+\r
+      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,\r
+        getLocale(aRequest));\r
+    }\r
+    catch (Throwable e) {\r
+      handleError(aRequest, aResponse, out, e);\r
+    }\r
+  }\r
+\r
+  private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,\r
+    PrintWriter out, EntityUsers userEntity) {\r
+    String startTemplate = "templates/admin/start_admin.template";\r
+    String sessionUrl = aResponse.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
+\r
+      if (messageModule == null) {\r
+        messageModule = new ModuleMessage(DatabaseMessages.getInstance());\r
+      }\r
+\r
+      mergeData.put("messages",\r
+        messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));\r
+\r
+      mergeData.put("articletypes",\r
+        DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));\r
+\r
+      HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,\r
+        getLocale(aRequest));\r
+    }\r
+    catch (Exception e) {\r
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+      handleError(aRequest, aResponse, out, e);\r
+    }\r
+  }\r
+\r
+  public String getServletInfo() {\r
+    return "Mir " + configuration.getString("Mir.Version");\r
+  }\r
+\r
+  private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {\r
+    // a lang parameter always sets the language\r
+    String lang = aRequest.getParameter("language");\r
+\r
+    if (lang != null) {\r
+      logger.info("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
+      logger.info("accept-language is " + aRequest.getLocale().getLanguage());\r
+      setLanguage(session, aRequest.getLocale().getLanguage());\r
+      setLocale(session, aRequest.getLocale());\r
+    }\r
+  }\r
+}\r
index ca0377c..3a0a5fa 100755 (executable)
@@ -57,7 +57,7 @@ import freemarker.template.SimpleScalar;
  *  OpenMir.java - main servlet for open posting and comment feature to articles
  *
  *  @author RK 1999-2001, the mir-coders group
- *  @version $Id: OpenMir.java,v 1.22 2003/03/06 05:40:38 zapata Exp $
+ *  @version $Id: OpenMir.java,v 1.23 2003/03/07 00:50:22 zapata Exp $
  *
  */
 
@@ -118,25 +118,23 @@ public class OpenMir extends AbstractServlet {
       SimpleHash modelRoot = new SimpleHash();
       modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
-      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.OpenIndy.UserErrorTemplate"),
                                     modelRoot, out, aRequest.getLocale() );
       out.close();
     }
     catch (Exception e) {
       logger.error("Error in UserErrorTemplate");
     }
-
   }
 
   private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
-
     try {
       logger.error("error: " + anException);
       SimpleHash modelRoot = new SimpleHash();
       modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
                                                new GregorianCalendar())));
-      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.OpenIndy.ErrorTemplate"),
                                     modelRoot,out, aRequest.getLocale());
       out.close();
     }