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 freemarker.template.SimpleList;
33 import freemarker.template.SimpleHash;
34 import freemarker.template.SimpleScalar;
35 import mir.misc.HTMLParseException;
36 import mir.misc.HTMLTemplateProcessor;
37 import mir.misc.MirConfig;
38 import mir.misc.StringUtil;
40 import mir.producer.*;
42 import mircoders.global.*;
43 import mircoders.localizer.*;
44 import mircoders.entity.EntityUsers;
45 import mircoders.module.ModuleMessage;
46 import mircoders.module.ModuleUsers;
47 import mircoders.storage.DatabaseArticleType;
48 import mircoders.storage.DatabaseMessages;
49 import mircoders.storage.DatabaseUsers;
51 import javax.servlet.ServletException;
52 import javax.servlet.UnavailableException;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
55 import javax.servlet.http.HttpSession;
56 import java.io.IOException;
57 import java.io.PrintWriter;
58 import java.lang.reflect.Method;
59 import java.util.GregorianCalendar;
60 import java.util.HashMap;
61 import java.util.Locale;
67 * Mir.java - main servlet, that dispatches to servletmodules
69 * @author $Author: mh $
70 * @version $Id: Mir.java,v 1.22 2002/11/04 04:35:20 mh Exp $
75 public class Mir extends AbstractServlet {
77 private static ModuleUsers usersModule = null;
78 private static ModuleMessage messageModule = null;
79 private final static HashMap servletModuleInstanceHash = new HashMap();
81 public HttpSession session;
83 public void doGet(HttpServletRequest req, HttpServletResponse res)
84 throws ServletException, IOException {
88 public void doPost(HttpServletRequest req, HttpServletResponse res)
89 throws ServletException, IOException, UnavailableException {
93 long startTime = System.currentTimeMillis();
94 long sessionConnectTime = 0;
95 EntityUsers userEntity;
98 // get the configration - this could conflict if 2 mirs are in the
99 // VM maybe? to be checked. -mh
100 if (getServletContext().getAttribute("mir.confed") == null) {
103 MirConfig.setServletName(getServletName());
106 // Log.info(this, "blalalala");
108 session = req.getSession(true);
109 userEntity = (EntityUsers) session.getAttribute("login.uid");
111 if (req.getServerPort() == 443) http = "https"; else http = "http";
112 res.setContentType("text/html; charset="
113 +MirConfig.getProp("Mir.DefaultEncoding"));
114 String moduleName = req.getParameter("module");
116 checkLanguage(session, req);
118 /** @todo for cleanup and readability this should be moved to
119 * method loginIfNecessary() */
121 if (moduleName!=null && moduleName.equals("direct")) {
126 if ((moduleName != null && moduleName.equals("login")) || (userEntity==null)) {
127 String user = req.getParameter("login");
128 String passwd = req.getParameter("password");
129 theLog.printDebugInfo("--login: evaluating for user: " + user);
130 userEntity = allowedUser(user, passwd);
131 if (userEntity == null) {
132 // login failed: redirecting to login
133 theLog.printWarning("--login: failed!");
134 _sendLoginPage(res, req, res.getWriter());
137 else if (moduleName!=null && moduleName.equals("login")) {
140 theLog.printInfo("--login: successful! setting uid: " + userEntity.getId());
141 session.setAttribute("login.uid", userEntity);
142 theLog.printDebugInfo("--login: trying to retrieve login.target");
143 String target = (String) session.getAttribute("login.target");
145 if (target != null) {
146 theLog.printDebugInfo("Redirect: " + target);
147 int serverPort = req.getServerPort();
148 String redirect = "";
149 String redirectString = "";
152 if (serverPort == 80) {
153 redirect = res.encodeURL(http + "://" + req.getServerName() + target);
154 redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
156 + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
159 redirect = res.encodeURL(http + "://" + req.getServerName() + ":" + req.getServerPort() + target);
160 redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
162 + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
164 res.getWriter().println(redirectString);
167 //res.sendRedirect(redirect);
171 // redirecting to default target
172 theLog.printDebugInfo("--login: no target - redirecting to default");
173 _sendStartPage(res, req, res.getWriter(), userEntity);
176 } // if login succesful
179 if (moduleName != null && moduleName.equals("logout")) {
180 theLog.printDebugInfo("--logout");
181 session.invalidate();
183 //session = req.getSession(true);
184 //checkLanguage(session, req);
185 _sendLoginPage(res, req, res.getWriter());
190 if (userEntity == null) {
191 // redirect to loginpage
192 String redirectString = req.getRequestURI();
193 String queryString = req.getQueryString();
194 if (queryString != null && !queryString.equals("")) {
195 redirectString += "?" + req.getQueryString();
196 theLog.printDebugInfo("STORING: " + redirectString);
197 session.setAttribute("login.target", redirectString);
199 _sendLoginPage(res, req, res.getWriter());
203 // If no module is specified goto standard startpage
204 if (moduleName == null || moduleName.equals("")) {
205 theLog.printDebugInfo("no module: redirect to standardpage");
206 _sendStartPage(res, req, res.getWriter(), userEntity);
211 // From now on regular dispatching...
213 // get servletmodule by parameter and continue with dispacher
214 ServletModule smod = getServletModuleForName(moduleName);
215 ServletModuleDispatch.dispatch(smod, req, res);
217 catch (ServletModuleException e) {
218 handleError(req, res, res.getWriter(),
219 "ServletException in Module " + moduleName + " -- " + e.getMessage());
221 catch (ServletModuleUserException e) {
222 handleUserError(req, res, res.getWriter(), e.getMessage());
226 sessionConnectTime = System.currentTimeMillis() - startTime;
227 theLog.printInfo("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
232 * Private method getServletModuleForName returns ServletModule
235 * @return ServletModule
238 private static ServletModule getServletModuleForName(String moduleName)
239 throws ServletModuleException {
242 if (!servletModuleInstanceHash.containsKey(moduleName)) {
243 // was not found in hash...
245 Class theServletModuleClass = null;
247 // first we try to get ServletModule from stern.che3.servlet
248 theServletModuleClass = Class.forName("mircoders.servlet.ServletModule" + moduleName);
250 catch (ClassNotFoundException e) {
251 // on failure, we try to get it from lib-layer
252 theServletModuleClass = Class.forName("mir.servlet.ServletModule" + moduleName);
254 Method m = theServletModuleClass.getMethod("getInstance", null);
255 ServletModule smod = (ServletModule) m.invoke(null, null);
256 // we put it into map for further reference
257 servletModuleInstanceHash.put(moduleName, smod);
260 catch (Exception e) {
261 throw new ServletModuleException("*** error resolving classname for " +
262 moduleName + " -- " + e.getMessage());
266 return (ServletModule) servletModuleInstanceHash.get(moduleName);
270 private void handleError(HttpServletRequest req, HttpServletResponse res,
271 PrintWriter out, String errorString) {
274 theLog.printError(errorString);
275 SimpleHash modelRoot = new SimpleHash();
276 modelRoot.put("errorstring", new SimpleScalar(errorString));
277 modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
278 HTMLTemplateProcessor.process(res, MirConfig.getProp("Mir.ErrorTemplate"), modelRoot, out, getLocale(req));
281 catch (Exception e) {
282 e.printStackTrace(System.out);
283 System.err.println("Error in ErrorTemplate: " + e.getMessage());
287 private void handleUserError(HttpServletRequest req, HttpServletResponse res,
288 PrintWriter out, String errorString) {
290 theLog.printError(errorString);
291 SimpleHash modelRoot = new SimpleHash();
292 modelRoot.put("errorstring", new SimpleScalar(errorString));
293 modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
294 HTMLTemplateProcessor.process(res, MirConfig.getProp("Mir.UserErrorTemplate"),
295 modelRoot, out, getLocale(req));
298 catch (Exception e) {
299 System.err.println("Error in UserErrorTemplate");
305 * evaluate login for user / password
307 protected EntityUsers allowedUser(String user, String password) {
309 if (usersModule == null) usersModule = new ModuleUsers(DatabaseUsers.getInstance());
310 return usersModule.getUserForLogin(user, password);
312 catch (Exception e) {
313 theLog.printDebugInfo(e.getMessage());
320 private void _sendLoginPage(HttpServletResponse res, HttpServletRequest req, PrintWriter out) {
321 String loginTemplate = MirConfig.getProp("Mir.LoginTemplate");//"login.template";
322 // theLog.printDebugInfo("login template: "+loginTemplate);
323 String sessionUrl = res.encodeURL("");
324 //session = req.getSession(true);
326 //theLog.printDebugInfo("login: "+lang);
328 // lang=getAcceptLanguage(req);
330 SimpleHash mergeData = new SimpleHash();
331 mergeData.put("session", sessionUrl);
332 HTMLTemplateProcessor.process(res, loginTemplate, mergeData, out, getLocale(req));
334 catch (HTMLParseException e) {
335 handleError(req, res, out, "Error in logintemplate.");
339 private void _sendStartPage(HttpServletResponse res, HttpServletRequest req, PrintWriter out, EntityUsers userEntity) {
340 String startTemplate = "templates/admin/start_admin.template";
341 String sessionUrl = res.encodeURL("");
343 // merge with logged in user and messages
344 SimpleHash mergeData = new SimpleHash();
345 mergeData.put("session", sessionUrl);
346 mergeData.put("login_user", userEntity);
347 if (messageModule == null) messageModule = new ModuleMessage(DatabaseMessages.getInstance());
348 mergeData.put("messages", messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
350 mergeData.put("articletypes", DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
353 SimpleList producersData = new SimpleList();
354 Iterator i = MirGlobal.localizer().producers().factories().entrySet().iterator();
355 while (i.hasNext()) {
356 Map.Entry entry = (Map.Entry) i.next();
358 SimpleList producerVerbs = new SimpleList();
359 Iterator j = ((ProducerFactory) entry.getValue()).verbs();
360 while (j.hasNext()) {
361 producerVerbs.add((String) j.next());
364 SimpleHash producerData = new SimpleHash();
365 producerData.put("key", (String) entry.getKey());
366 producerData.put("verbs", producerVerbs);
368 producersData.add(producerData);
370 mergeData.put("producers", producersData);
374 HTMLTemplateProcessor.process(res, startTemplate, mergeData, out, getLocale(req));
376 catch (Exception e) {
377 e.printStackTrace(System.out);
378 handleError(req, res, out, "error while trying to send startpage. " + e.getMessage());
382 public String getServletInfo() {
383 return "Mir "+MirConfig.getProp("Mir.Version");
386 private void checkLanguage(HttpSession session, HttpServletRequest req) {
388 // a lang parameter always sets the language
389 String lang = req.getParameter("lang");
391 theLog.printInfo("selected language "+lang+" overrides accept-language");
392 setLanguage(session, lang);
393 setLocale(session, new Locale(lang, ""));
395 // otherwise store language from accept header in session
396 else if (session.getAttribute("Language") == null) {
397 theLog.printInfo("accept-language is "+req.getLocale().getLanguage());
398 setLanguage(session, req.getLocale().getLanguage());
399 setLocale(session, req.getLocale());