2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
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.
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.
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
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.
31 import mir.bundle.Bundle;
32 import mir.config.MirPropertiesConfiguration;
34 import mir.util.ExceptionFunctions;
35 import mir.util.StringRoutines;
36 import mir.log.LoggerWrapper;
37 import mircoders.entity.EntityUsers;
38 import mircoders.global.MirGlobal;
39 import mircoders.module.ModuleUsers;
40 import mircoders.servlet.ServletHelper;
42 import javax.servlet.ServletConfig;
43 import javax.servlet.ServletException;
44 import javax.servlet.UnavailableException;
45 import javax.servlet.http.*;
46 import java.io.IOException;
47 import java.io.PrintWriter;
48 import java.lang.reflect.Method;
52 * Mir.java - main servlet, that dispatches to servletmodules
54 * @author $Author: idfx $
57 public class Mir extends AbstractServlet {
58 private static ModuleUsers usersModule = null;
59 private final static Map servletModuleInstanceHash = new HashMap();
60 private static Locale fallbackLocale = null;
62 private static List loginLanguages = null;
64 protected List getLoginLanguages() throws ServletException {
65 synchronized (Mir.class) {
67 if (loginLanguages == null) {
69 StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
71 loginLanguages = new ArrayList();
73 Iterator i = languages.iterator();
76 String code = (String) i.next();
79 MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new String[] { code });
80 Bundle defaultBundle =
81 MirGlobal.getBundleFactory().getBundle("bundles/admin", new String[] { code });
83 String name = bundle.getValue("languagename", Collections.EMPTY_LIST);
86 name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST);
93 Map record = new HashMap();
94 record.put("name", name);
95 record.put("code", code);
96 loginLanguages.add(record);
100 return loginLanguages;
102 catch (Throwable t) {
103 throw new ServletException(t.getMessage());
108 public void init(ServletConfig config) throws ServletException {
111 usersModule = new ModuleUsers();
114 protected String getDefaultLanguage(HttpServletRequest aRequest) {
115 String defaultlanguage =
116 MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
118 if (defaultlanguage.length() == 0) {
119 Locale locale = aRequest.getLocale();
120 defaultlanguage = locale.getLanguage();
123 return defaultlanguage;
126 protected synchronized Locale getFallbackLocale() throws ServletException {
128 if (fallbackLocale == null) {
129 fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
132 catch (Throwable t) {
133 throw new ServletException(t.getMessage());
136 return fallbackLocale;
139 public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {
141 EntityUsers user = ServletHelper.getUser(aRequest);
143 String username = aRequest.getParameter("login");
144 String password = aRequest.getParameter("password");
146 if (username != null && password != null) {
147 user = usersModule.getUserForLogin(username, password);
150 ServletHelper.setUser(aRequest, user);
151 usersModule.recordLogin(user);
152 aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId()));
158 catch (Throwable t) {
161 throw new ServletException(t.toString());
165 public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {
167 long startTime = System.currentTimeMillis();
168 long sessionConnectTime = 0;
170 HttpSession session = aRequest.getSession(true);
171 setNoCaching(aResponse);
172 aResponse.setContentType("text/html; charset=" +
174 getString("Mir.DefaultHTMLCharset", "UTF-8"));
176 EntityUsers userEntity = checkCredentials(aRequest);
178 if (userEntity == null) {
179 String queryString = aRequest.getQueryString();
181 if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&
182 (aRequest.getParameter("module")==null ||
183 (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {
184 session.setAttribute("login.target", queryString);
187 _sendLoginPage(aResponse, aRequest);
190 String moduleName = aRequest.getParameter("module");
191 checkLanguage(session, aRequest);
193 if ( ( (moduleName == null) || moduleName.equals(""))) {
198 if (moduleName.equals("login")) {
199 String target = (String) session.getAttribute("login.target");
201 if (target != null) {
202 ServletHelper.redirect(aResponse, target);
205 ServletHelper.redirect(aResponse, "");
208 else if (moduleName.equals("logout")) {
209 logger.info(userEntity.getFieldValue("login") + " has logged out");
210 session.invalidate();
211 _sendLoginPage(aResponse, aRequest);
216 ServletModule servletModule = getServletModuleForName(moduleName);
217 ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);
219 sessionConnectTime = System.currentTimeMillis() - startTime;
220 logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
222 catch (Throwable e) {
223 Throwable cause = ExceptionFunctions.traceCauseException(e);
225 if (cause instanceof ServletModuleUserExc)
226 handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
228 handleError(aRequest, aResponse, cause);
231 if (aRequest.getParameter("killsession")!=null)
232 aRequest.getSession().invalidate();
236 catch (Throwable t) {
237 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
239 throw new ServletException(t.toString());
244 * caching routine to get a module for a module name
246 * @param moduleName the module name
247 * @return the requested module
248 * @throws ServletModuleExc
251 private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
253 if (!servletModuleInstanceHash.containsKey(moduleName)) {
254 // was not found in hash...
256 Class theServletModuleClass = null;
259 // first we try to get ServletModule from stern.che3.servlet
260 theServletModuleClass =
261 Class.forName("mircoders.servlet.ServletModule" + moduleName);
263 catch (ClassNotFoundException e) {
264 // on failure, we try to get it from lib-layer
265 theServletModuleClass =
266 Class.forName("mir.servlet.ServletModule" + moduleName);
269 Method m = theServletModuleClass.getMethod("getInstance", null);
270 ServletModule smod = (ServletModule) m.invoke(null, null);
272 // we put it into map for further reference
273 servletModuleInstanceHash.put(moduleName, smod);
277 catch (Exception e) {
278 throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
282 return (ServletModule) servletModuleInstanceHash.get(moduleName);
286 private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
288 logger.info("user error: " + anException.getMessage());
290 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
293 MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new
294 String[] { getLocale(aRequest).getLanguage() });
295 Bundle defaultBundle =
296 MirGlobal.getBundleFactory().getBundle("bundles/admin", new
297 String[] { getLocale(aRequest).getLanguage() });
299 bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
303 defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
306 responseData.put("errorstring", message);
307 responseData.put("date", new GregorianCalendar().getTime());
309 ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));
311 catch (Throwable e) {
312 logger.error("Error handling user error" + e.toString());
316 private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {
318 logger.error("error: " + anException);
320 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
322 responseData.put("errorstring", anException.toString());
323 responseData.put("date", new GregorianCalendar().getTime());
325 ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
327 catch (Throwable e) {
328 logger.error("Error handling error: " + e.toString());
331 Throwable rootException = ExceptionFunctions.traceCauseException(anException);
333 PrintWriter writer = aResponse.getWriter();
334 writer.println("<html><head><title>FATAL Error</title><body>");
335 writer.println("<h1>" + rootException.toString()+"</h1>");
336 writer.println("<code>");
337 rootException.printStackTrace(writer);
338 writer.println("</code>");
339 writer.println("</body></html>");
342 catch (Throwable t) {
349 private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {
350 String loginTemplate = configuration.getString("Mir.LoginTemplate");
353 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
355 responseData.put("defaultlanguage", getDefaultLanguage(aRequest));
356 responseData.put("languages", getLoginLanguages());
358 ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);
360 catch (Throwable e) {
361 handleError(aRequest, aResponse, e);
365 public String getServletInfo() {
366 return "Mir " + configuration.getString("Mir.Version");
369 private class SessionTracker implements HttpSessionBindingListener {
373 public SessionTracker(String aUserName, String anId) {
378 public void valueBound(HttpSessionBindingEvent anEvent) {
379 MirGlobal.registerLogin(name, id);
382 public void valueUnbound(HttpSessionBindingEvent anEvent) {
383 MirGlobal.registerLogout(name, id);