cleaned up the login code
[mir.git] / source / mir / servlet / AbstractServlet.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  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mir.servlet;
31
32 import java.io.IOException;
33 import java.lang.reflect.InvocationTargetException;
34 import java.lang.reflect.Method;
35 import java.util.Locale;
36 import java.sql.*;
37
38 import javax.servlet.ServletConfig;
39 import javax.servlet.ServletException;
40 import javax.servlet.http.HttpServlet;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43 import javax.servlet.http.HttpSession;
44
45
46 import com.codestudio.util.*;
47 import com.codestudio.util.JDBCPoolMetaData;
48 import com.codestudio.util.SQLManager;
49
50 import mir.config.MirPropertiesConfiguration;
51 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
52 import mir.log.LoggerWrapper;
53 import mircoders.global.*;
54
55 /**
56  * Title:        Mir
57  * Description:  Abstract servlet-class
58  * Copyright:    Copyright (c) 2001, 2002
59  * Company:      Mir-coders group
60  * @author       idfx, the Mir-coders group
61  * @version      $Id: AbstractServlet.java,v 1.30.2.3 2003/06/28 04:04:25 zapata Exp $
62  */
63
64 public abstract class AbstractServlet extends HttpServlet {
65   protected static String lang;
66   protected LoggerWrapper logger;
67   protected MirPropertiesConfiguration configuration;
68
69   /**
70    * Constructor for AbstractServlet.
71    */
72   public AbstractServlet() {
73     super();
74   }
75
76   protected void setNoCaching(HttpServletResponse aResponse) {
77     //nothing in Mir can or should be cached as it's all dynamic...
78     //
79     //this needs to be done here and not per page (via meta tags) as some
80     //browsers have problems w/ it per-page -mh
81     aResponse.setHeader("Pragma", "no-cache");
82     aResponse.setDateHeader("Expires", 0);
83     aResponse.setHeader("Cache-Control", "no-cache");
84   }
85
86   /**
87    * Bind the language to the session
88    */
89   protected void setLanguage(HttpSession session, String language) {
90     logger.debug("setting language to " + language);
91
92     session.setAttribute("language", language);
93     session.setAttribute("locale", new Locale(language, ""));
94   }
95
96   /**
97    * Get the session-bound language
98    */
99   protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
100     String lang = (String) session.getAttribute("language");
101
102     if (lang == null || lang.length()==0) {
103       lang = getAcceptLanguage(aRequest);
104     }
105
106     return lang;
107   }
108
109   /**
110    * get the locale either from the session or the accept-language header ot the request
111    * this supersedes getLanguage for the new i18n
112    */
113   public Locale getLocale(HttpServletRequest aRequest) {
114     Locale loc = null;
115     HttpSession session = aRequest.getSession(false);
116     if (session != null) {
117       // session can be null in case of logout
118       loc = (Locale) session.getAttribute("locale");
119     }
120     // if there is nothing in the session get it fron the accept-language
121     if (loc == null) {
122       loc = aRequest.getLocale();
123     }
124
125     logger.debug("getting locale: " + loc.getLanguage());
126
127     return loc;
128   }
129
130   /**
131    * Checks the Accept-Language of the client browser.
132    * If this language is available it returns its country-code,
133    * else it returns the standard-language
134    */
135   protected String getAcceptLanguage(HttpServletRequest aRequest) {
136     Locale loc = aRequest.getLocale();
137     lang = loc.getLanguage();
138     return lang;
139   }
140
141   /**
142    * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
143    */
144   public void init(ServletConfig config) throws ServletException {
145     super.init(config);
146
147     MirPropertiesConfiguration.setContext(config.getServletContext());
148     try {
149       configuration = MirPropertiesConfiguration.instance();
150     }
151     catch (Throwable t) {
152       throw new ServletException("can't read configuration: " + t.toString());
153     }
154
155     logger = new LoggerWrapper("Servlet");
156
157     try {
158       MirGlobal.localizer();
159     }
160     catch (Throwable t) {
161       logger.fatal("can't get localizer: " + t.toString());
162       throw new ServletException("can't get localizer: " + t.toString());
163     }
164
165     String dbUser = configuration.getString("Database.Username");
166     String dbPassword = configuration.getString("Database.Password");
167     String dbHost = configuration.getString("Database.Host");
168     String dbPort = configuration.getString("Database.Port");
169     String dbAdapName = configuration.getString("Database.Adaptor");
170     String dbName = configuration.getString("Database.Name");
171     String dbDriver = configuration.getString("Database.Driver");
172     String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;
173     int dbMin = configuration.getInteger("Database.poolMin", 1);
174     int dbMax = configuration.getInteger("Database.poolMax", 10);
175
176     JDBCPoolMetaData meta = new JDBCPoolMetaData();
177     meta.setDbname(dbName);
178     meta.setDriver(dbDriver);
179     meta.setURL(dbUrl);
180     meta.setUserName(dbUser);
181     meta.setPassword(dbPassword);
182     meta.setJNDIName("mir");
183     meta.setMaximumSize(dbMax);
184     meta.setMinimumSize(dbMin);
185     meta.setPoolPreparedStatements(false);
186     meta.setCacheEnabled(false);
187     meta.setCacheSize(15);
188     meta.setDebugging(false);
189
190     SQLManager manager = SQLManager.getInstance();
191
192     JDBCPool pool = null;
193     if (manager != null) {
194       pool = manager.createPool(meta);
195     }
196
197     Connection connection;
198     try {
199       connection = pool.requestConnection();
200       pool.closeConnection(connection);
201     }
202     catch (Throwable t) {
203       logger.fatal("Can't connect to database: " + t.toString());
204       throw new ServletException("Can't connect to database: " + t.toString());
205     }
206   }
207
208   private void setEncoding(HttpServletRequest request){
209     try {
210       Class reqClass = request.getClass();
211       Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
212       String encoding = configuration.getString("Mir.DefaultHTMLCharset");
213       method.invoke(request, new Object[]{encoding});
214     } catch (NoSuchMethodException e) {
215       // TODO set the encoding in a zapata-way
216 //      logger.warn("set encoding not yet implemented: " + e.getMessage());
217     } catch (SecurityException e) {
218       logger.error(e.getMessage());
219       e.printStackTrace();
220     } catch (IllegalArgumentException e) {
221       logger.error(e.getMessage());
222       e.printStackTrace();
223     } catch (IllegalAccessException e) {
224       logger.error(e.getMessage());
225       e.printStackTrace();
226     } catch (InvocationTargetException e) {
227       logger.error(e.getMessage());
228       e.printStackTrace();
229     }
230   }
231
232   protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
233     doPost(request, response);
234   }
235
236   protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
237     if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {
238       configuration.setProperty("RootUri", request.getContextPath());
239     }
240     setEncoding(request);
241     process(request, response);
242   }
243
244   abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
245
246   /**
247    * Selects the language for the response.
248    *
249    * @param session
250    * @param aRequest
251    */
252   protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {
253     String requestLanguage = aRequest.getParameter("language");
254     String sessionLanguage = (String) aSession.getAttribute("language");
255     String acceptLanguage = aRequest.getLocale().getLanguage();
256     String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
257
258     String language = requestLanguage;
259
260     if (language==null)
261       language = sessionLanguage;
262
263     if (language==null)
264       language = acceptLanguage;
265
266     if (language==null)
267       language = defaultLanguage;
268
269     setLanguage(aSession, language);
270   }
271 }