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 the com.oreilly.servlet library, any library
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24 * the above that use the same license as the above), and distribute linked
25 * combinations including the two. You must obey the GNU General Public
26 * License in all respects for all of the code used other than the above
27 * mentioned libraries. If you modify this file, you may extend this exception
28 * to your version of the file, but you are not obligated to do so. If you do
29 * not wish to do so, delete this exception statement from your version.
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.lang.reflect.Method;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Locale;
41 import java.util.Vector;
43 import javax.servlet.ServletException;
44 import javax.servlet.UnavailableException;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import javax.servlet.http.HttpSession;
49 import mir.config.MirPropertiesConfiguration;
50 import mir.generator.FreemarkerGenerator;
51 import mir.log.LoggerWrapper;
52 import mir.misc.HTMLTemplateProcessor;
53 import mir.misc.StringUtil;
54 import mir.servlet.AbstractServlet;
55 import mir.servlet.ServletModule;
56 import mir.servlet.ServletModuleDispatch;
57 import mir.servlet.ServletModuleExc;
58 import mir.servlet.ServletModuleUserExc;
59 import mir.util.ExceptionFunctions;
60 import mir.util.StringRoutines;
61 import mircoders.entity.EntityUsers;
62 import mircoders.global.MirGlobal;
63 import mircoders.module.ModuleMessage;
64 import mircoders.module.ModuleUsers;
65 import mircoders.storage.DatabaseArticleType;
66 import mircoders.storage.DatabaseMessages;
67 import mircoders.storage.DatabaseUsers;
69 import org.apache.struts.util.MessageResources;
71 import freemarker.template.SimpleHash;
72 import freemarker.template.SimpleList;
73 import freemarker.template.SimpleScalar;
74 import freemarker.template.TemplateModel;
80 * Mir.java - main servlet, that dispatches to servletmodules
82 * @author $Author: zapata $
83 * @version $Id: Mir.java,v 1.40 2003/03/15 15:35:56 zapata Exp $
86 public class Mir extends AbstractServlet {
87 private static ModuleUsers usersModule = null;
88 private static ModuleMessage messageModule = null;
89 private final static Map servletModuleInstanceHash = new HashMap();
91 //I don't know about making this static cause it removes the
92 //possibility to change the config on the fly.. -mh
93 private static List loginLanguages = null;
94 public HttpSession session;
96 protected TemplateModel getLoginLanguages() throws ServletException {
97 synchronized (Mir.class) {
99 if (loginLanguages == null) {
100 MessageResources messageResources2 =
101 MessageResources.getMessageResources("bundles.admin");
102 MessageResources messageResources =
103 MessageResources.getMessageResources("bundles.adminlocal");
105 StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
107 loginLanguages = new Vector();
109 Iterator i = languages.iterator();
111 while (i.hasNext()) {
112 String code = (String) i.next();
113 Locale locale = new Locale(code, "");
114 String name = messageResources.getMessage(locale, "languagename");
117 name = messageResources2.getMessage(locale, "languagename");
124 Map record = new HashMap();
125 record.put("name", name);
126 record.put("code", code);
127 loginLanguages.add(record);
131 return FreemarkerGenerator.makeAdapter(loginLanguages);
133 catch (Throwable t) {
134 throw new ServletException(t.getMessage());
139 // FIXME: this should probalby go into AbstractServlet so it can be used in
140 // OpenMir as well -mh
141 protected String getDefaultLanguage(HttpServletRequest aRequest) {
142 String defaultlanguage =
143 MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
145 if (defaultlanguage.length() == 0) {
146 Locale locale = aRequest.getLocale();
147 defaultlanguage = locale.getLanguage();
150 return defaultlanguage;
153 public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
154 throws ServletException, IOException, UnavailableException {
155 long startTime = System.currentTimeMillis();
156 long sessionConnectTime = 0;
157 EntityUsers userEntity;
160 configuration.addProperty("ServletName", getServletName());
162 session = aRequest.getSession(true);
163 userEntity = (EntityUsers) session.getAttribute("login.uid");
165 if (aRequest.getServerPort() == 443) {
171 //make sure client browsers don't cache anything
172 setNoCaching(aResponse);
174 //FIXME: this seems kind of hackish and only here because we can have
175 // default other than the one that the browser is set to.
176 Locale locale = new Locale(getDefaultLanguage(aRequest), "");
177 MessageResources messageResources =
178 MessageResources.getMessageResources("bundles.admin");
179 String htmlcharset = messageResources.getMessage(locale, "htmlcharset");
181 aResponse.setContentType("text/html; charset=" + htmlcharset);
183 String moduleName = aRequest.getParameter("module");
184 checkLanguage(session, aRequest);
186 /** @todo for cleanup and readability this should be moved to
187 * method loginIfNecessary() */
188 if ((moduleName != null) && moduleName.equals("direct")) {
193 if (((moduleName != null) && moduleName.equals("login")) ||
194 (userEntity == null)) {
195 String user = aRequest.getParameter("login");
196 String passwd = aRequest.getParameter("password");
197 logger.debug("--login: evaluating for user: " + user);
198 userEntity = allowedUser(user, passwd);
200 if (userEntity == null) {
201 // login failed: redirecting to login
202 logger.warn("--login: failed!");
203 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
206 } else if ((moduleName != null) && moduleName.equals("login")) {
208 logger.info("--login: successful! setting uid: " + userEntity.getId());
209 session.setAttribute("login.uid", userEntity);
210 logger.debug("--login: trying to retrieve login.target");
212 String target = (String) session.getAttribute("login.target");
214 if (target != null) {
215 logger.debug("Redirect: " + target);
217 int serverPort = aRequest.getServerPort();
218 String redirect = "";
219 String redirectString = "";
221 if (serverPort == 80) {
223 aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
225 "<html><head><meta http-equiv=refresh content=\"1;URL=" +
226 redirect + "\"></head><body>going <a href=\"" + redirect +
227 "\">Mir</a></body></html>";
230 aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
231 aRequest.getServerPort() + target);
233 "<html><head><meta http-equiv=refresh content=\"1;URL=" +
234 redirect + "\"></head><body>going <a href=\"" + redirect +
235 "\">Mir</a></body></html>";
238 aResponse.getWriter().println(redirectString);
240 //aResponse.sendRedirect(redirect);
242 // redirecting to default target
243 logger.debug("--login: no target - redirecting to default");
244 _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
249 // if login succesful
253 if ((moduleName != null) && moduleName.equals("logout")) {
254 logger.info("--logout");
255 session.invalidate();
257 //session = aRequest.getSession(true);
258 //checkLanguage(session, aRequest);
259 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
265 if (userEntity == null) {
266 // redirect to loginpage
267 String redirectString = aRequest.getRequestURI();
268 String queryString = aRequest.getQueryString();
270 if ((queryString != null) && !queryString.equals("")) {
271 redirectString += ("?" + aRequest.getQueryString());
272 logger.debug("STORING: " + redirectString);
273 session.setAttribute("login.target", redirectString);
276 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
281 // If no module is specified goto standard startpage
282 if ((moduleName == null) || moduleName.equals("")) {
283 logger.debug("no module: redirect to standardpage");
284 _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
290 // From now on regular dispatching...
292 // get servletmodule by parameter and continue with dispacher
293 ServletModule smod = getServletModuleForName(moduleName);
294 ServletModuleDispatch.dispatch(smod, aRequest, aResponse);
296 catch (Throwable e) {
297 Throwable cause = ExceptionFunctions.traceCauseException(e);
299 if (cause instanceof ServletModuleUserExc)
300 handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
302 handleError(aRequest, aResponse, aResponse.getWriter(), cause);
307 sessionConnectTime = System.currentTimeMillis() - startTime;
308 logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
312 * Private method getServletModuleForName returns ServletModule
316 * @return ServletModule
319 private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
321 if (!servletModuleInstanceHash.containsKey(moduleName)) {
322 // was not found in hash...
324 Class theServletModuleClass = null;
327 // first we try to get ServletModule from stern.che3.servlet
328 theServletModuleClass =
329 Class.forName("mircoders.servlet.ServletModule" + moduleName);
330 } catch (ClassNotFoundException e) {
331 // on failure, we try to get it from lib-layer
332 theServletModuleClass =
333 Class.forName("mir.servlet.ServletModule" + moduleName);
336 Method m = theServletModuleClass.getMethod("getInstance", null);
337 ServletModule smod = (ServletModule) m.invoke(null, null);
339 // we put it into map for further reference
340 servletModuleInstanceHash.put(moduleName, smod);
344 catch (Exception e) {
345 throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
349 return (ServletModule) servletModuleInstanceHash.get(moduleName);
353 private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
354 PrintWriter out, ServletModuleUserExc anException) {
356 logger.info("user error: " + anException.getMessage());
357 SimpleHash modelRoot = new SimpleHash();
358 MessageResources messages = MessageResources.getMessageResources("bundles.admin");
359 modelRoot.put("errorstring",
361 messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())
363 modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
364 HTMLTemplateProcessor.process(
365 aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
366 modelRoot, out, getLocale(aRequest));
369 catch (Exception e) {
370 logger.error("Error in UserErrorTemplate");
375 private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
378 logger.error("error: " + anException);
379 SimpleHash modelRoot = new SimpleHash();
380 modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
381 modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
382 new GregorianCalendar())));
383 HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
384 modelRoot,out, getLocale(aRequest));
387 catch (Exception e) {
388 logger.error("Error in ErrorTemplate");
393 * evaluate login for user / password
395 protected EntityUsers allowedUser(String user, String password) {
397 if (usersModule == null) {
398 usersModule = new ModuleUsers(DatabaseUsers.getInstance());
401 return usersModule.getUserForLogin(user, password);
403 catch (Exception e) {
404 logger.debug(e.getMessage());
405 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
412 private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
414 String loginTemplate = configuration.getString("Mir.LoginTemplate");
415 String sessionUrl = aResponse.encodeURL("");
418 SimpleHash mergeData = new SimpleHash();
419 SimpleList languages = new SimpleList();
421 mergeData.put("session", sessionUrl);
423 mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
424 mergeData.put("languages", getLoginLanguages());
426 HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,
427 getLocale(aRequest));
429 catch (Throwable e) {
430 handleError(aRequest, aResponse, out, e);
434 private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
435 PrintWriter out, EntityUsers userEntity) {
436 String startTemplate = "templates/admin/start_admin.template";
437 String sessionUrl = aResponse.encodeURL("");
440 // merge with logged in user and messages
441 SimpleHash mergeData = new SimpleHash();
442 mergeData.put("session", sessionUrl);
443 mergeData.put("login_user", userEntity);
445 if (messageModule == null) {
446 messageModule = new ModuleMessage(DatabaseMessages.getInstance());
449 mergeData.put("messages",
450 messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
452 mergeData.put("articletypes",
453 DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
455 HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,
456 getLocale(aRequest));
458 catch (Exception e) {
459 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
460 handleError(aRequest, aResponse, out, e);
464 public String getServletInfo() {
465 return "Mir " + configuration.getString("Mir.Version");
468 private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
469 // a lang parameter always sets the language
470 String lang = aRequest.getParameter("language");
473 logger.info("selected language " + lang + " overrides accept-language");
474 setLanguage(session, lang);
475 setLocale(session, new Locale(lang, ""));
477 // otherwise store language from accept header in session
478 else if (session.getAttribute("Language") == null) {
479 logger.info("accept-language is " + aRequest.getLocale().getLanguage());
480 setLanguage(session, aRequest.getLocale().getLanguage());
481 setLocale(session, aRequest.getLocale());