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 java.io.IOException;
32 import java.io.PrintWriter;
33 import java.lang.reflect.Method;
34 import java.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Locale;
40 import java.util.Vector;
41 import javax.servlet.ServletException;
42 import javax.servlet.UnavailableException;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45 import javax.servlet.http.HttpSession;
47 import org.apache.struts.util.MessageResources;
48 import freemarker.template.SimpleHash;
49 import freemarker.template.SimpleList;
50 import freemarker.template.SimpleScalar;
51 import freemarker.template.TemplateModel;
53 import mir.config.MirPropertiesConfiguration;
54 import mir.entity.adapter.EntityIteratorAdapter;
55 import mir.generator.FreemarkerGenerator;
56 import mir.log.LoggerWrapper;
57 import mir.misc.HTMLTemplateProcessor;
58 import mir.misc.StringUtil;
59 import mir.servlet.AbstractServlet;
60 import mir.servlet.ServletModule;
61 import mir.servlet.ServletModuleDispatch;
62 import mir.servlet.ServletModuleExc;
63 import mir.servlet.ServletModuleUserExc;
64 import mir.util.CachingRewindableIterator;
65 import mir.util.ExceptionFunctions;
66 import mir.util.StringRoutines;
67 import mircoders.entity.EntityUsers;
68 import mircoders.global.MirGlobal;
69 import mircoders.module.ModuleMessage;
70 import mircoders.module.ModuleUsers;
71 import mircoders.servlet.ServletHelper;
72 import mircoders.servlet.ServletModuleFileEdit;
73 import mircoders.servlet.ServletModuleLocalizer;
74 import mircoders.storage.DatabaseUsers;
80 * Mir.java - main servlet, that dispatches to servletmodules
82 * @author $Author: zapata $
83 * @version $Id: Mir.java,v 1.49 2003/05/08 02:43:41 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();
90 private static Locale fallbackLocale = null;
92 //I don't know about making this static cause it removes the
93 //possibility to change the config on the fly.. -mh
94 private static List loginLanguages = null;
96 protected TemplateModel getLoginLanguages() throws ServletException {
97 synchronized (Mir.class) {
99 if (loginLanguages == null) {
100 MessageResources messageResources =
101 MessageResources.getMessageResources("bundles.adminlocal");
102 MessageResources messageResources2 =
103 MessageResources.getMessageResources("bundles.admin");
106 StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
108 loginLanguages = new Vector();
110 Iterator i = languages.iterator();
112 while (i.hasNext()) {
113 String code = (String) i.next();
114 Locale locale = new Locale(code, "");
115 String name = messageResources.getMessage(locale, "languagename");
118 name = messageResources2.getMessage(locale, "languagename");
125 Map record = new HashMap();
126 record.put("name", name);
127 record.put("code", code);
128 loginLanguages.add(record);
132 return FreemarkerGenerator.makeAdapter(loginLanguages);
134 catch (Throwable t) {
135 throw new ServletException(t.getMessage());
140 // FIXME: this should probalby go into AbstractServlet so it can be used in
141 // OpenMir as well -mh
142 protected String getDefaultLanguage(HttpServletRequest aRequest) {
143 String defaultlanguage =
144 MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
146 if (defaultlanguage.length() == 0) {
147 Locale locale = aRequest.getLocale();
148 defaultlanguage = locale.getLanguage();
151 return defaultlanguage;
154 protected synchronized Locale getFallbackLocale() throws ServletException {
156 if (fallbackLocale == null) {
157 fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
160 catch (Throwable t) {
161 throw new ServletException(t.getMessage());
164 return fallbackLocale;
167 public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
168 throws ServletException, IOException, UnavailableException {
169 long startTime = System.currentTimeMillis();
170 long sessionConnectTime = 0;
171 EntityUsers userEntity;
175 configuration.addProperty("ServletName", getServletName());
177 session = aRequest.getSession(true);
178 userEntity = (EntityUsers) session.getAttribute("login.uid");
180 if (aRequest.getServerPort() == 443) {
187 setNoCaching(aResponse);
189 Locale locale = new Locale(getDefaultLanguage(aRequest), "");
191 aResponse.setContentType("text/html; charset=" +
192 configuration.getString("Mir.DefaultHTMLCharset", "UTF-8"));
194 String moduleName = aRequest.getParameter("module");
195 checkLanguage(session, aRequest);
198 if (((moduleName != null) && moduleName.equals("login")) || (userEntity == null)) {
199 String user = aRequest.getParameter("login");
200 String passwd = aRequest.getParameter("password");
201 logger.debug("--login: evaluating for user: " + user);
202 userEntity = allowedUser(user, passwd);
204 if (userEntity == null) {
205 // login failed: redirecting to login
206 logger.warn("--login: failed!");
207 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
211 else if ((moduleName != null) && moduleName.equals("login")) {
213 logger.info("--login: successful! setting uid: " + userEntity.getId());
214 session.setAttribute("login.uid", userEntity);
215 logger.debug("--login: trying to retrieve login.target");
217 String target = (String) session.getAttribute("login.target");
219 if (target != null) {
220 logger.debug("Redirect: " + target);
222 int serverPort = aRequest.getServerPort();
223 String redirect = "";
224 String redirectString = "";
226 if (serverPort == 80) {
228 aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
230 "<html><head><meta http-equiv=refresh content=\"1;URL=" +
231 redirect + "\"></head><body>going <a href=\"" + redirect +
232 "\">Mir</a></body></html>";
235 aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
236 aRequest.getServerPort() + target);
238 "<html><head><meta http-equiv=refresh content=\"1;URL=" +
239 redirect + "\"></head><body>going <a href=\"" + redirect +
240 "\">Mir</a></body></html>";
243 aResponse.getWriter().println(redirectString);
245 //aResponse.sendRedirect(redirect);
247 // redirecting to default target
248 logger.debug("--login: no target - redirecting to default");
249 _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
254 // if login succesful
258 if ((moduleName != null) && moduleName.equals("logout")) {
259 logger.info("--logout");
260 session.invalidate();
262 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
268 if (userEntity == null) {
269 // redirect to loginpage
270 String redirectString = aRequest.getRequestURI();
271 String queryString = aRequest.getQueryString();
273 if ((queryString != null) && queryString.length()!=0) {
274 redirectString += ("?" + aRequest.getQueryString());
275 session.setAttribute("login.target", redirectString);
278 _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
283 // If no module is specified goto standard startpage
284 if ((moduleName == null) || moduleName.equals("")) {
285 // logger.debug("no module: redirect to standardpage");
286 _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
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(
366 MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
374 catch (Throwable e) {
375 logger.error("Error handling user error" + e.toString());
380 private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
383 logger.error("error: " + anException);
384 SimpleHash modelRoot = new SimpleHash();
385 modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
386 modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
387 new GregorianCalendar())));
388 HTMLTemplateProcessor.process(
389 aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
390 modelRoot,null,out, getLocale(aRequest), getFallbackLocale());
393 catch (Throwable e) {
394 logger.error("Error handling error: " + e.toString());
399 * evaluate login for user / password
401 protected EntityUsers allowedUser(String user, String password) {
403 if (usersModule == null) {
404 usersModule = new ModuleUsers(DatabaseUsers.getInstance());
407 return usersModule.getUserForLogin(user, password);
409 catch (Exception e) {
410 logger.debug(e.getMessage());
411 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
418 private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
420 String loginTemplate = configuration.getString("Mir.LoginTemplate");
421 String sessionUrl = aResponse.encodeURL("");
424 SimpleHash mergeData = new SimpleHash();
425 SimpleList languages = new SimpleList();
427 mergeData.put("session", sessionUrl);
429 mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
430 mergeData.put("languages", getLoginLanguages());
432 HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale());
434 catch (Throwable e) {
435 handleError(aRequest, aResponse, out, e);
439 private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
440 PrintWriter out, EntityUsers userEntity) {
441 String startTemplate = configuration.getString("Mir.StartTemplate");
442 String sessionUrl = aResponse.encodeURL("");
445 Map mergeData = ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}, "bundles.admin", "bundles.adminlocal");
446 mergeData.put("messages",
447 new CachingRewindableIterator(
448 new EntityIteratorAdapter( "", "webdb_create desc", 10,
449 MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
451 mergeData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
452 mergeData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
454 mergeData.put("searchvalue", null);
455 mergeData.put("searchfield", null);
456 mergeData.put("searchispublished", null);
457 mergeData.put("searcharticletype", null);
458 mergeData.put("searchorder", null);
459 mergeData.put("selectarticleurl", null);
461 ServletHelper.generateResponse(out, mergeData, startTemplate);
463 catch (Exception e) {
464 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
465 handleError(aRequest, aResponse, out, e);
469 public String getServletInfo() {
470 return "Mir " + configuration.getString("Mir.Version");
473 private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
474 // a lang parameter always sets the language
475 String lang = aRequest.getParameter("language");
478 logger.info("selected language " + lang + " overrides accept-language");
479 setLanguage(session, lang);
481 // otherwise store language from accept header in session
482 else if (session.getAttribute("language") == null) {
483 logger.info("accept-language is " + aRequest.getLocale().getLanguage());
484 setLanguage(session, aRequest.getLocale().getLanguage());