Organizing import, refresh the license (zapata deleted cos.jar)
[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
37 import javax.servlet.ServletConfig;
38 import javax.servlet.ServletException;
39 import javax.servlet.http.HttpServlet;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.servlet.http.HttpSession;
43
44 import mir.config.MirPropertiesConfiguration;
45 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
46 import mir.log.LoggerWrapper;
47 import mir.storage.DatabaseAdaptor;
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.29 2003/04/21 12:42:50 idfx 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     logger = new LoggerWrapper("Servlet");
73   }
74
75   protected void setNoCaching(HttpServletResponse aResponse) {
76     //nothing in Mir can or should be cached as it's all dynamic...
77     //
78     //this needs to be done here and not per page (via meta tags) as some
79     //browsers have problems w/ it per-page -mh
80     aResponse.setHeader("Pragma", "no-cache");
81     aResponse.setDateHeader("Expires", 0);
82     aResponse.setHeader("Cache-Control", "no-cache");
83   }
84
85   /**
86    * Bind the language to the session
87    */
88   protected void setLanguage(HttpSession session, String language) {
89     logger.debug("setting language to " + language);
90
91     session.setAttribute("language", language);
92     session.setAttribute("locale", new Locale(language, ""));
93   }
94
95   /**
96    * Get the session-bound language
97    */
98   protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
99     String lang = (String) session.getAttribute("language");
100
101     if (lang == null || lang.length()==0) {
102       lang = getAcceptLanguage(aRequest);
103     }
104
105     return lang;
106   }
107
108   /**
109    * get the locale either from the session or the accept-language header ot the request
110    * this supersedes getLanguage for the new i18n
111    */
112   public Locale getLocale(HttpServletRequest aRequest) {
113     Locale loc = null;
114     HttpSession session = aRequest.getSession(false);
115     if (session != null) {
116       // session can be null in case of logout
117       loc = (Locale) session.getAttribute("locale");
118     }
119     // if there is nothing in the session get it fron the accept-language
120     if (loc == null) {
121       loc = aRequest.getLocale();
122     }
123
124     logger.debug("getting locale: " + loc.getLanguage());
125
126     return loc;
127   }
128
129   /**
130    * Checks the Accept-Language of the client browser.
131    * If this language is available it returns its country-code,
132    * else it returns the standard-language
133    */
134   protected String getAcceptLanguage(HttpServletRequest aRequest) {
135     Locale loc = aRequest.getLocale();
136     lang = loc.getLanguage();
137     return lang;
138   }
139
140   /**
141    * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
142    */
143   public void init(ServletConfig config) throws ServletException {
144     super.init(config);
145
146     MirPropertiesConfiguration.setContext(config.getServletContext());
147     try {
148       configuration = MirPropertiesConfiguration.instance();
149     }
150     catch (PropertiesConfigExc e) {
151       throw new ServletException(e);
152     }
153
154     String dbUser = configuration.getString("Database.Username");
155     String dbPassword = configuration.getString("Database.Password");
156     String dbHost = configuration.getString("Database.Host");
157     String dbAdapName = configuration.getString("Database.Adaptor");
158     String dbName = configuration.getString("Database.Name");
159
160     DatabaseAdaptor adaptor;
161     try {
162       adaptor = (DatabaseAdaptor) Class.forName(dbAdapName).newInstance();
163     }
164     catch (Exception e) {
165       throw new ServletException("Could not load DB adapator: " +
166                                  e.toString());
167     }
168
169     String dbDriver;
170     String dbUrl;
171     try {
172       dbDriver = adaptor.getDriver();
173       dbUrl = adaptor.getURL(dbUser, dbPassword, dbHost);
174     }
175     catch (Exception e) {
176       throw new ServletException(e);
177     }
178
179     JDBCPoolMetaData meta = new JDBCPoolMetaData();
180     meta.setDbname(dbName);
181     meta.setDriver(dbDriver);
182     meta.setURL(dbUrl);
183     meta.setUserName(dbUser);
184     meta.setPassword(dbPassword);
185     meta.setJNDIName("mir");
186     meta.setMaximumSize(10);
187     meta.setMinimumSize(1);
188     meta.setPoolPreparedStatements(false);
189     meta.setCacheEnabled(false);
190     meta.setCacheSize(15);
191     meta.setDebugging(false);
192 //    meta.setLogFile(dblogfile+".pool");
193
194     SQLManager manager = SQLManager.getInstance();
195     JDBCPool pool = null;
196     if (manager != null) {
197       pool = manager.createPool(meta);
198     }
199   }
200   
201   private void setEncoding(HttpServletRequest request){
202         try {
203                         Class reqClass = request.getClass();
204                         Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
205                         String encoding = configuration.getString("Mir.DefaultHTMLCharset");
206                         method.invoke(request, new Object[]{encoding});                 
207                 } catch (NoSuchMethodException e) {
208                         // TODO set the encoding in a zapata-way
209                         e.printStackTrace();
210                         logger.error("not yes implemented: " + e.getMessage());
211                 } catch (SecurityException e) {
212                         logger.error(e.getMessage());
213                         e.printStackTrace();
214                 } catch (IllegalArgumentException e) {
215                         logger.error(e.getMessage());
216                         e.printStackTrace();
217                 } catch (IllegalAccessException e) {
218                         logger.error(e.getMessage());
219                         e.printStackTrace();
220                 } catch (InvocationTargetException e) {
221                         logger.error(e.getMessage());
222                         e.printStackTrace();
223                 }
224   }
225
226   protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
227     doPost(request, response);
228   }
229
230   protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
231     if ( (configuration.getString("RootUri") == null) ||
232         configuration.getString("RootUri").equals("")) {
233       configuration.setProperty("RootUri", request.getContextPath());
234     }
235     setEncoding(request);
236     process(request, response);
237   }
238
239   abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
240
241 }