image bugfixx - mir now depends on jai imagio
[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.5 2003/10/23 14:55:26 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     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     Connection connection;
196     try {
197       connection = pool.requestConnection();
198           JDBCPool.closeConnection(connection);
199     }
200     catch (Throwable t) {
201       logger.fatal("Can't connect to database: " + t.toString());
202       throw new ServletException("Can't connect to database: " + t.toString());
203     }
204   }
205
206   private void setEncoding(HttpServletRequest request){
207     try {
208       logger.info("Request has encoding: " + request.getCharacterEncoding());
209       logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));
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       logger.info("Request now has encoding: " + request.getCharacterEncoding());
215     }
216     catch (NoSuchMethodException e) {
217       // TODO set the encoding in a zapata-way
218 //      logger.warn("set encoding not yet implemented: " + e.getMessage());
219     }
220     catch (SecurityException e) {
221       logger.error(e.getMessage());
222       e.printStackTrace();
223     }
224     catch (IllegalArgumentException e) {
225       logger.error(e.getMessage());
226       e.printStackTrace();
227     }
228     catch (IllegalAccessException e) {
229       logger.error(e.getMessage());
230       e.printStackTrace();
231     }
232     catch (InvocationTargetException e) {
233       logger.error(e.getMessage());
234       e.printStackTrace();
235     }
236   }
237
238   protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
239     doPost(request, response);
240   }
241
242   protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
243     if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {
244       configuration.setProperty("RootUri", request.getContextPath());
245     }
246     setEncoding(request);
247     process(request, response);
248   }
249
250   abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
251
252   /**
253    * Selects the language for the response.
254    *
255    * @param session
256    * @param aRequest
257    */
258   protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {
259     String requestLanguage = aRequest.getParameter("language");
260     String sessionLanguage = (String) aSession.getAttribute("language");
261     String acceptLanguage = aRequest.getLocale().getLanguage();
262     String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
263
264     String language = requestLanguage;
265
266     if (language==null)
267       language = sessionLanguage;
268
269     if (language==null)
270       language = acceptLanguage;
271
272     if (language==null)
273       language = defaultLanguage;
274
275     setLanguage(aSession, language);
276   }
277 }