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