bugfix
[mir.git] / source / Mir.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
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.
10  *
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.
15  *
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
19  *
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.
29  */
30
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;
39 import java.util.Map;
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;
46
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;
52
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;
75
76
77
78
79 /**
80  * Mir.java - main servlet, that dispatches to servletmodules
81  *
82  * @author $Author: zapata $
83  * @version $Id: Mir.java,v 1.49 2003/05/08 02:43:41 zapata Exp $
84  *
85  */
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;
91
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;
95
96   protected TemplateModel getLoginLanguages() throws ServletException {
97     synchronized (Mir.class) {
98       try {
99         if (loginLanguages == null) {
100           MessageResources messageResources =
101             MessageResources.getMessageResources("bundles.adminlocal");
102           MessageResources messageResources2 =
103             MessageResources.getMessageResources("bundles.admin");
104
105           List languages =
106             StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
107
108           loginLanguages = new Vector();
109
110           Iterator i = languages.iterator();
111
112           while (i.hasNext()) {
113             String code = (String) i.next();
114             Locale locale = new Locale(code, "");
115             String name = messageResources.getMessage(locale, "languagename");
116
117             if (name == null) {
118               name = messageResources2.getMessage(locale, "languagename");
119             }
120
121             if (name == null) {
122               name = code;
123             }
124
125             Map record = new HashMap();
126             record.put("name", name);
127             record.put("code", code);
128             loginLanguages.add(record);
129           }
130         }
131
132         return FreemarkerGenerator.makeAdapter(loginLanguages);
133       }
134       catch (Throwable t) {
135         throw new ServletException(t.getMessage());
136       }
137     }
138   }
139
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", "");
145
146     if (defaultlanguage.length() == 0) {
147       Locale locale = aRequest.getLocale();
148       defaultlanguage = locale.getLanguage();
149     }
150
151     return defaultlanguage;
152   }
153
154   protected synchronized Locale getFallbackLocale() throws ServletException {
155     try {
156       if (fallbackLocale == null) {
157         fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
158       }
159     }
160     catch (Throwable t) {
161       throw new ServletException(t.getMessage());
162     }
163
164     return fallbackLocale;
165   }
166
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;
172     HttpSession session;
173     String http = "";
174
175     configuration.addProperty("ServletName", getServletName());
176
177     session = aRequest.getSession(true);
178     userEntity = (EntityUsers) session.getAttribute("login.uid");
179
180     if (aRequest.getServerPort() == 443) {
181       http = "https";
182     }
183     else {
184       http = "http";
185     }
186
187     setNoCaching(aResponse);
188
189     Locale locale = new Locale(getDefaultLanguage(aRequest), "");
190
191     aResponse.setContentType("text/html; charset=" +
192         configuration.getString("Mir.DefaultHTMLCharset", "UTF-8"));
193
194     String moduleName = aRequest.getParameter("module");
195     checkLanguage(session, aRequest);
196
197     // Authentication
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);
203
204       if (userEntity == null) {
205         // login failed: redirecting to login
206         logger.warn("--login: failed!");
207         _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
208
209         return;
210       }
211       else if ((moduleName != null) && moduleName.equals("login")) {
212         // login successful
213         logger.info("--login: successful! setting uid: " + userEntity.getId());
214         session.setAttribute("login.uid", userEntity);
215         logger.debug("--login: trying to retrieve login.target");
216
217         String target = (String) session.getAttribute("login.target");
218
219         if (target != null) {
220           logger.debug("Redirect: " + target);
221
222           int serverPort = aRequest.getServerPort();
223           String redirect = "";
224           String redirectString = "";
225
226           if (serverPort == 80) {
227             redirect =
228               aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
229             redirectString =
230               "<html><head><meta http-equiv=refresh content=\"1;URL=" +
231               redirect + "\"></head><body>going <a href=\"" + redirect +
232               "\">Mir</a></body></html>";
233           } else {
234             redirect =
235               aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
236                 aRequest.getServerPort() + target);
237             redirectString =
238               "<html><head><meta http-equiv=refresh content=\"1;URL=" +
239               redirect + "\"></head><body>going <a href=\"" + redirect +
240               "\">Mir</a></body></html>";
241           }
242
243           aResponse.getWriter().println(redirectString);
244
245           //aResponse.sendRedirect(redirect);
246         } else {
247           // redirecting to default target
248           logger.debug("--login: no target - redirecting to default");
249           _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
250         }
251
252         return;
253       }
254        // if login succesful
255     }
256      // if login
257
258     if ((moduleName != null) && moduleName.equals("logout")) {
259       logger.info("--logout");
260       session.invalidate();
261
262       _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
263
264       return;
265     }
266
267     // Check if authed!
268     if (userEntity == null) {
269       // redirect to loginpage
270       String redirectString = aRequest.getRequestURI();
271       String queryString = aRequest.getQueryString();
272
273       if ((queryString != null) && queryString.length()!=0) {
274         redirectString += ("?" + aRequest.getQueryString());
275         session.setAttribute("login.target", redirectString);
276       }
277
278       _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
279
280       return;
281     }
282
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);
287
288       return;
289     }
290
291     try {
292       // get servletmodule by parameter and continue with dispacher
293       ServletModule smod = getServletModuleForName(moduleName);
294       ServletModuleDispatch.dispatch(smod, aRequest, aResponse);
295     }
296     catch (Throwable e) {
297       Throwable cause = ExceptionFunctions.traceCauseException(e);
298
299       if (cause instanceof ServletModuleUserExc)
300         handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
301       else
302         handleError(aRequest, aResponse, aResponse.getWriter(), cause);
303
304     }
305
306     // timing...
307     sessionConnectTime = System.currentTimeMillis() - startTime;
308     logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
309   }
310
311   /**
312    *  Private method getServletModuleForName returns ServletModule
313    *  from Cache
314    *
315    * @param moduleName
316    * @return ServletModule
317    *
318    */
319   private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
320     // Instance in Map ?
321     if (!servletModuleInstanceHash.containsKey(moduleName)) {
322       // was not found in hash...
323       try {
324         Class theServletModuleClass = null;
325
326         try {
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);
334         }
335
336         Method m = theServletModuleClass.getMethod("getInstance", null);
337         ServletModule smod = (ServletModule) m.invoke(null, null);
338
339         // we put it into map for further reference
340         servletModuleInstanceHash.put(moduleName, smod);
341
342         return smod;
343       }
344       catch (Exception e) {
345         throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
346       }
347     }
348     else {
349       return (ServletModule) servletModuleInstanceHash.get(moduleName);
350     }
351   }
352
353   private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
354                                PrintWriter out, ServletModuleUserExc anException) {
355     try {
356       logger.info("user error: " + anException.getMessage());
357       SimpleHash modelRoot = new SimpleHash();
358       MessageResources messages = MessageResources.getMessageResources("bundles.admin");
359       modelRoot.put("errorstring",
360           new SimpleScalar(
361               messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())
362           ));
363       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
364       HTMLTemplateProcessor.process(
365           aResponse,
366           MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
367           modelRoot,
368           null,
369           out,
370           getLocale(aRequest),
371           fallbackLocale);
372       out.close();
373     }
374     catch (Throwable e) {
375       logger.error("Error handling user error" + e.toString());
376     }
377
378   }
379
380   private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
381
382     try {
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());
391       out.close();
392     }
393     catch (Throwable e) {
394       logger.error("Error handling error: " + e.toString());
395     }
396   }
397
398   /**
399    *  evaluate login for user / password
400    */
401   protected EntityUsers allowedUser(String user, String password) {
402     try {
403       if (usersModule == null) {
404         usersModule = new ModuleUsers(DatabaseUsers.getInstance());
405       }
406
407       return usersModule.getUserForLogin(user, password);
408     }
409     catch (Exception e) {
410       logger.debug(e.getMessage());
411       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
412
413       return null;
414     }
415   }
416
417   // Redirect-methods
418   private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
419     PrintWriter out) {
420     String loginTemplate = configuration.getString("Mir.LoginTemplate");
421     String sessionUrl = aResponse.encodeURL("");
422
423     try {
424       SimpleHash mergeData = new SimpleHash();
425       SimpleList languages = new SimpleList();
426
427       mergeData.put("session", sessionUrl);
428
429       mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
430       mergeData.put("languages", getLoginLanguages());
431
432       HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale());
433     }
434     catch (Throwable e) {
435       handleError(aRequest, aResponse, out, e);
436     }
437   }
438
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("");
443
444     try {
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)));
450
451       mergeData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
452       mergeData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
453
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);
460
461       ServletHelper.generateResponse(out, mergeData, startTemplate);
462     }
463     catch (Exception e) {
464       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
465       handleError(aRequest, aResponse, out, e);
466     }
467   }
468
469   public String getServletInfo() {
470     return "Mir " + configuration.getString("Mir.Version");
471   }
472
473   private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
474     // a lang parameter always sets the language
475     String lang = aRequest.getParameter("language");
476
477     if (lang != null) {
478       logger.info("selected language " + lang + " overrides accept-language");
479       setLanguage(session, lang);
480     }
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());
485     }
486   }
487 }