small bugfixes
[mir.git] / source / mir / servlet / AbstractServlet.java
index ef0d592..5308bcc 100755 (executable)
-/*
- * 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  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 java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Locale;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.log.LoggerWrapper;
-import mir.storage.DatabaseAdaptor;
-
-import com.codestudio.util.JDBCPool;
-import com.codestudio.util.JDBCPoolMetaData;
-import com.codestudio.util.SQLManager;
-
-/**
- * Title:        Mir
- * Description:  Abstract servlet-class
- * Copyright:    Copyright (c) 2001, 2002
- * Company:      Mir-coders group
- * @author       idfx, the Mir-coders group
- * @version      $Id: AbstractServlet.java,v 1.29 2003/04/21 12:42:50 idfx Exp $
- */
-
-public abstract class AbstractServlet extends HttpServlet {
-  protected static String lang;
-  protected LoggerWrapper logger;
-  protected MirPropertiesConfiguration configuration;
-
-  /**
-   * Constructor for AbstractServlet.
-   */
-  public AbstractServlet() {
-    super();
-    logger = new LoggerWrapper("Servlet");
-  }
-
-  protected void setNoCaching(HttpServletResponse aResponse) {
-    //nothing in Mir can or should be cached as it's all dynamic...
-    //
-    //this needs to be done here and not per page (via meta tags) as some
-    //browsers have problems w/ it per-page -mh
-    aResponse.setHeader("Pragma", "no-cache");
-    aResponse.setDateHeader("Expires", 0);
-    aResponse.setHeader("Cache-Control", "no-cache");
-  }
-
-  /**
-   * Bind the language to the session
-   */
-  protected void setLanguage(HttpSession session, String language) {
-    logger.debug("setting language to " + language);
-
-    session.setAttribute("language", language);
-    session.setAttribute("locale", new Locale(language, ""));
-  }
-
-  /**
-   * Get the session-bound language
-   */
-  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
-    String lang = (String) session.getAttribute("language");
-
-    if (lang == null || lang.length()==0) {
-      lang = getAcceptLanguage(aRequest);
-    }
-
-    return lang;
-  }
-
-  /**
-   * 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 aRequest) {
-    Locale loc = null;
-    HttpSession session = aRequest.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 = aRequest.getLocale();
-    }
-
-    logger.debug("getting locale: " + loc.getLanguage());
-
-    return loc;
-  }
-
-  /**
-   * Checks the Accept-Language of the client browser.
-   * If this language is available it returns its country-code,
-   * else it returns the standard-language
-   */
-  protected String getAcceptLanguage(HttpServletRequest aRequest) {
-    Locale loc = aRequest.getLocale();
-    lang = loc.getLanguage();
-    return lang;
-  }
-
-  /**
-   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
-   */
-  public void init(ServletConfig config) throws ServletException {
-    super.init(config);
-
-    MirPropertiesConfiguration.setContext(config.getServletContext());
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new ServletException(e);
-    }
-
-    String dbUser = configuration.getString("Database.Username");
-    String dbPassword = configuration.getString("Database.Password");
-    String dbHost = configuration.getString("Database.Host");
-    String dbAdapName = configuration.getString("Database.Adaptor");
-    String dbName = configuration.getString("Database.Name");
-
-    DatabaseAdaptor adaptor;
-    try {
-      adaptor = (DatabaseAdaptor) Class.forName(dbAdapName).newInstance();
-    }
-    catch (Exception e) {
-      throw new ServletException("Could not load DB adapator: " +
-                                 e.toString());
-    }
-
-    String dbDriver;
-    String dbUrl;
-    try {
-      dbDriver = adaptor.getDriver();
-      dbUrl = adaptor.getURL(dbUser, dbPassword, dbHost);
-    }
-    catch (Exception e) {
-      throw new ServletException(e);
-    }
-
-    JDBCPoolMetaData meta = new JDBCPoolMetaData();
-    meta.setDbname(dbName);
-    meta.setDriver(dbDriver);
-    meta.setURL(dbUrl);
-    meta.setUserName(dbUser);
-    meta.setPassword(dbPassword);
-    meta.setJNDIName("mir");
-    meta.setMaximumSize(10);
-    meta.setMinimumSize(1);
-    meta.setPoolPreparedStatements(false);
-    meta.setCacheEnabled(false);
-    meta.setCacheSize(15);
-    meta.setDebugging(false);
-//    meta.setLogFile(dblogfile+".pool");
-
-    SQLManager manager = SQLManager.getInstance();
-    JDBCPool pool = null;
-    if (manager != null) {
-      pool = manager.createPool(meta);
-    }
-  }
-  
-  private void setEncoding(HttpServletRequest request){
-       try {
-                       Class reqClass = request.getClass();
-                       Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
-                       String encoding = configuration.getString("Mir.DefaultHTMLCharset");
-                       method.invoke(request, new Object[]{encoding});                 
-               } catch (NoSuchMethodException e) {
-                       // TODO set the encoding in a zapata-way
-                       e.printStackTrace();
-                       logger.error("not yes implemented: " + e.getMessage());
-               } catch (SecurityException e) {
-                       logger.error(e.getMessage());
-                       e.printStackTrace();
-               } catch (IllegalArgumentException e) {
-                       logger.error(e.getMessage());
-                       e.printStackTrace();
-               } catch (IllegalAccessException e) {
-                       logger.error(e.getMessage());
-                       e.printStackTrace();
-               } catch (InvocationTargetException e) {
-                       logger.error(e.getMessage());
-                       e.printStackTrace();
-               }
-  }
-
-  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    doPost(request, response);
-  }
-
-  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    if ( (configuration.getString("RootUri") == null) ||
-        configuration.getString("RootUri").equals("")) {
-      configuration.setProperty("RootUri", request.getContextPath());
-    }
-    setEncoding(request);
-    process(request, response);
-  }
-
-  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
-
-}
+/*\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  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import java.io.IOException;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.lang.reflect.Method;\r
+import java.sql.Connection;\r
+import java.util.Locale;\r
+\r
+import javax.servlet.ServletConfig;\r
+import javax.servlet.ServletException;\r
+import javax.servlet.http.HttpServlet;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import com.codestudio.util.JDBCPool;\r
+import com.codestudio.util.JDBCPoolMetaData;\r
+import com.codestudio.util.SQLManager;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.log.LoggerWrapper;\r
+\r
+import mircoders.global.MirGlobal;\r
+\r
+/**\r
+ * Title:        Mir\r
+ * Description:  Abstract servlet-class\r
+ * Copyright:    Copyright (c) 2001, 2002\r
+ * Company:      Mir-coders group\r
+ * @author       idfx, the Mir-coders group\r
+ * @version      $Id: AbstractServlet.java,v 1.31 2003/09/03 18:29:03 zapata Exp $\r
+ */\r
+\r
+public abstract class AbstractServlet extends HttpServlet {\r
+  protected static String lang;\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+\r
+  /**\r
+   * Constructor for AbstractServlet.\r
+   */\r
+  public AbstractServlet() {\r
+    super();\r
+  }\r
+\r
+  protected void setNoCaching(HttpServletResponse aResponse) {\r
+    //nothing in Mir can or should be cached as it's all dynamic...\r
+    //\r
+    //this needs to be done here and not per page (via meta tags) as some\r
+    //browsers have problems w/ it per-page -mh\r
+    aResponse.setHeader("Pragma", "no-cache");\r
+    aResponse.setDateHeader("Expires", 0);\r
+    aResponse.setHeader("Cache-Control", "no-cache");\r
+  }\r
+\r
+  /**\r
+   * Bind the language to the session\r
+   */\r
+  protected void setLanguage(HttpSession session, String language) {\r
+    logger.debug("setting language to " + language);\r
+\r
+    session.setAttribute("language", language);\r
+    session.setAttribute("locale", new Locale(language, ""));\r
+  }\r
+\r
+  /**\r
+   * Get the session-bound language\r
+   */\r
+  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {\r
+    String lang = (String) session.getAttribute("language");\r
+\r
+    if (lang == null || lang.length()==0) {\r
+      lang = getAcceptLanguage(aRequest);\r
+    }\r
+\r
+    return lang;\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public Locale getLocale(HttpServletRequest aRequest) {\r
+    Locale loc = null;\r
+    HttpSession session = aRequest.getSession(false);\r
+    if (session != null) {\r
+      // session can be null in case of logout\r
+      loc = (Locale) session.getAttribute("locale");\r
+    }\r
+    // if there is nothing in the session get it fron the accept-language\r
+    if (loc == null) {\r
+      loc = aRequest.getLocale();\r
+    }\r
+\r
+    logger.debug("getting locale: " + loc.getLanguage());\r
+\r
+    return loc;\r
+  }\r
+\r
+  /**\r
+   * Checks the Accept-Language of the client browser.\r
+   * If this language is available it returns its country-code,\r
+   * else it returns the standard-language\r
+   */\r
+  protected String getAcceptLanguage(HttpServletRequest aRequest) {\r
+    Locale loc = aRequest.getLocale();\r
+    lang = loc.getLanguage();\r
+    return lang;\r
+  }\r
+\r
+  /**\r
+   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)\r
+   */\r
+  public void init(ServletConfig config) throws ServletException {\r
+    super.init(config);\r
+\r
+    MirPropertiesConfiguration.setContext(config.getServletContext());\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletException("can't read configuration: " + t.toString());\r
+    }\r
+\r
+    logger = new LoggerWrapper("Servlet");\r
+\r
+    try {\r
+      MirGlobal.localizer();\r
+    }\r
+    catch (Throwable t) {\r
+      logger.fatal("can't get localizer: " + t.toString());\r
+      throw new ServletException("can't get localizer: " + t.toString());\r
+    }\r
+\r
+    String dbUser = configuration.getString("Database.Username");\r
+    String dbPassword = configuration.getString("Database.Password");\r
+    String dbHost = configuration.getString("Database.Host");\r
+    String dbPort = configuration.getString("Database.Port");\r
+    String dbAdapName = configuration.getString("Database.Adaptor");\r
+    String dbName = configuration.getString("Database.Name");\r
+    String dbDriver = configuration.getString("Database.Driver");\r
+    String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;\r
+    int dbMin = configuration.getInteger("Database.poolMin", 1);\r
+    int dbMax = configuration.getInteger("Database.poolMax", 10);\r
+\r
+    JDBCPoolMetaData meta = new JDBCPoolMetaData();\r
+    meta.setDbname(dbName);\r
+    meta.setDriver(dbDriver);\r
+    meta.setURL(dbUrl);\r
+    meta.setUserName(dbUser);\r
+    meta.setPassword(dbPassword);\r
+    meta.setJNDIName("mir");\r
+    meta.setMaximumSize(dbMax);\r
+    meta.setMinimumSize(dbMin);\r
+    meta.setPoolPreparedStatements(false);\r
+    meta.setCacheEnabled(false);\r
+    meta.setCacheSize(15);\r
+    meta.setDebugging(false);\r
+\r
+    SQLManager manager = SQLManager.getInstance();\r
+\r
+    JDBCPool pool = null;\r
+    if (manager != null) {\r
+      pool = manager.createPool(meta);\r
+    }\r
+\r
+    Connection connection;\r
+    try {\r
+      connection = pool.requestConnection();\r
+      pool.closeConnection(connection);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.fatal("Can't connect to database: " + t.toString());\r
+      throw new ServletException("Can't connect to database: " + t.toString());\r
+    }\r
+  }\r
+\r
+  private void setEncoding(HttpServletRequest request){\r
+    try {\r
+      logger.info("Request has encoding: " + request.getCharacterEncoding());\r
+      logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));\r
+      Class reqClass = request.getClass();\r
+      Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});\r
+      String encoding = configuration.getString("Mir.DefaultHTMLCharset");\r
+      method.invoke(request, new Object[]{encoding});\r
+      logger.info("Request now has encoding: " + request.getCharacterEncoding());\r
+    }\r
+    catch (NoSuchMethodException e) {\r
+      // TODO set the encoding in a zapata-way\r
+//      logger.warn("set encoding not yet implemented: " + e.getMessage());\r
+    }\r
+    catch (SecurityException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (IllegalArgumentException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (IllegalAccessException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (InvocationTargetException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+  }\r
+\r
+  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
+    doPost(request, response);\r
+  }\r
+\r
+  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
+    if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {\r
+      configuration.setProperty("RootUri", request.getContextPath());\r
+    }\r
+    setEncoding(request);\r
+    process(request, response);\r
+  }\r
+\r
+  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;\r
+\r
+  /**\r
+   * Selects the language for the response.\r
+   *\r
+   * @param session\r
+   * @param aRequest\r
+   */\r
+  protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {\r
+    String requestLanguage = aRequest.getParameter("language");\r
+    String sessionLanguage = (String) aSession.getAttribute("language");\r
+    String acceptLanguage = aRequest.getLocale().getLanguage();\r
+    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");\r
+\r
+    String language = requestLanguage;\r
+\r
+    if (language==null)\r
+      language = sessionLanguage;\r
+\r
+    if (language==null)\r
+      language = acceptLanguage;\r
+\r
+    if (language==null)\r
+      language = defaultLanguage;\r
+\r
+    setLanguage(aSession, language);\r
+  }\r
+}\r