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;
33 import mir.log.LoggerWrapper;
35 import mir.util.StringRoutines;
36 import mir.util.ExceptionRoutines;
37 import multex.Failure;
39 import javax.servlet.ServletConfig;
40 import javax.servlet.ServletException;
41 import javax.servlet.UnavailableException;
42 import javax.servlet.http.*;
43 import java.io.IOException;
44 import java.io.PrintWriter;
45 import java.io.StringWriter;
48 import mircoders.module.ModuleUsers;
49 import mircoders.global.MirGlobal;
50 import mircoders.servlet.ServletHelper;
51 import mircoders.entity.EntityUsers;
53 public class Mir extends AbstractServlet {
54 private static ModuleUsers usersModule = null;
55 private static Locale fallbackLocale = null;
57 private static List loginLanguages = null;
59 private List getLoginLanguages() throws Failure {
60 synchronized (Mir.class) {
62 if (loginLanguages == null) {
64 StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
66 loginLanguages = new ArrayList();
68 Iterator i = languages.iterator();
71 String code = (String) i.next();
74 MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new String[] { code });
75 Bundle defaultBundle =
76 MirGlobal.getBundleFactory().getBundle("bundles/admin", new String[] { code });
78 String name = bundle.getValue("languagename", Collections.EMPTY_LIST);
81 name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST);
88 Map record = new HashMap();
89 record.put("name", name);
90 record.put("code", code);
91 loginLanguages.add(record);
95 return loginLanguages;
98 throw new Failure("Error while retrieving the available login languages", t);
103 public void init(ServletConfig config) throws ServletException {
106 usersModule = new ModuleUsers();
109 protected String getDefaultLanguage(HttpServletRequest aRequest) {
110 String defaultlanguage =
111 MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
113 if (defaultlanguage.length() == 0) {
114 Locale locale = aRequest.getLocale();
115 defaultlanguage = locale.getLanguage();
118 return defaultlanguage;
121 protected synchronized Locale getFallbackLocale() throws ServletException {
123 if (fallbackLocale == null) {
124 fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
127 catch (Throwable t) {
128 throw new ServletException(t.getMessage());
131 return fallbackLocale;
134 public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {
136 EntityUsers user = ServletHelper.getUser(aRequest);
138 String username = aRequest.getParameter("login");
139 String password = aRequest.getParameter("password");
141 if (username != null && password != null) {
142 user = usersModule.getUserForLogin(username, password);
145 ServletHelper.setUser(aRequest, user);
146 usersModule.recordLogin(user);
147 aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId()));
153 catch (Throwable t) {
154 throw new ServletException(t.getMessage());
158 public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {
160 long startTime = System.currentTimeMillis();
161 long sessionConnectTime = 0;
163 HttpSession session = aRequest.getSession(true);
164 setNoCaching(aResponse);
165 aResponse.setContentType("text/html; charset=" +
167 getString("Mir.DefaultHTMLCharset", "UTF-8"));
169 EntityUsers userEntity = checkCredentials(aRequest);
171 if (userEntity == null) {
172 String queryString = aRequest.getQueryString();
174 if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&
175 (aRequest.getParameter("module")==null ||
176 (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {
177 session.setAttribute("login.target", queryString);
180 _sendLoginPage(aResponse, aRequest);
183 String moduleName = aRequest.getParameter("module");
184 checkLanguage(session, aRequest);
186 if ( ( (moduleName == null) || moduleName.equals(""))) {
190 if (moduleName.equals("login")) {
191 String target = (String) session.getAttribute("login.target");
193 if (target != null) {
194 ServletHelper.redirect(aResponse, target);
197 ServletHelper.redirect(aResponse, "");
200 else if (moduleName.equals("logout")) {
201 logger.info(userEntity.getFieldValue("login") + " has logged out");
202 session.invalidate();
203 _sendLoginPage(aResponse, aRequest);
208 AdminServletModule servletModule = getServletModuleForName(moduleName);
209 servletModule.handleRequest(aRequest, aResponse);
211 sessionConnectTime = System.currentTimeMillis() - startTime;
212 logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
214 catch (Throwable e) {
215 Throwable cause = ExceptionRoutines.traceCauseException(e);
217 if (cause instanceof ServletModuleUserExc)
218 handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
220 handleError(aRequest, aResponse, cause);
223 if (aRequest.getParameter("killsession")!=null)
224 aRequest.getSession().invalidate();
228 catch (Throwable t) {
229 throw new ServletException(t.toString());
234 * caching routine to get a module for a module name
236 * @param aModuleName the module name
237 * @return the requested module
238 * @throws ServletModuleExc
240 private static AdminServletModule getServletModuleForName(String aModuleName) throws ServletModuleExc {
241 return ServletHelper.getServletModule(aModuleName);
244 private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
246 logger.info("user error: " + anException.getMessage());
248 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
251 MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new
252 String[] { getLocale(aRequest).getLanguage() });
253 Bundle defaultBundle =
254 MirGlobal.getBundleFactory().getBundle("bundles/admin", new
255 String[] { getLocale(aRequest).getLanguage() });
257 bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
261 defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
264 responseData.put("errorstring", message);
265 responseData.put("date", new GregorianCalendar().getTime());
267 ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));
269 catch (Throwable e) {
270 logger.error("Error handling user error" + e.toString());
274 private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {
276 logger.error("error: " + anException);
278 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
280 responseData.put("errorstring", anException.toString());
281 StringWriter writer = new StringWriter();
282 anException.printStackTrace(new PrintWriter(writer));
283 responseData.put("stacktrace", writer.toString());
284 responseData.put("date", new GregorianCalendar().getTime());
286 ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
288 catch (Throwable e) {
289 logger.error("Error handling error: " + e.toString());
292 Throwable rootException = ExceptionRoutines.traceCauseException(anException);
294 PrintWriter writer = aResponse.getWriter();
295 writer.println("<html><head><title>FATAL Error</title><body>");
296 writer.println("<h1>" + rootException.toString()+"</h1>");
297 writer.println("<code>");
298 rootException.printStackTrace(writer);
299 writer.println("</code>");
300 writer.println("</body></html>");
303 catch (Throwable t) {
310 private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {
311 String loginTemplate = configuration.getString("Mir.LoginTemplate");
314 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
316 responseData.put("defaultlanguage", getDefaultLanguage(aRequest));
317 responseData.put("languages", getLoginLanguages());
319 ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);
321 catch (Throwable e) {
322 handleError(aRequest, aResponse, e);
326 public String getServletInfo() {
327 return "Mir " + configuration.getString("Mir.Version");
330 private class SessionTracker implements HttpSessionBindingListener {
334 public SessionTracker(String aUserName, String anId) {
339 public void valueBound(HttpSessionBindingEvent anEvent) {
340 MirGlobal.registerLogin(name, id);
343 public void valueUnbound(HttpSessionBindingEvent anEvent) {
344 MirGlobal.registerLogout(name, id);