merge media InputStream changes from MIR_1_0 branch
[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 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.
30  */
31
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;
39 import mir.servlet.*;
40 import mir.producer.*;
41
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;
50
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;
62 import java.util.*;
63
64 import mir.log.Log;
65
66 /**
67  * Mir.java - main servlet, that dispatches to servletmodules
68  *
69  * @author $Author: mh $
70  * @version $Id: Mir.java,v 1.22 2002/11/04 04:35:20 mh Exp $
71  *
72  */
73
74
75 public class Mir extends AbstractServlet {
76
77     private static ModuleUsers usersModule = null;
78     private static ModuleMessage messageModule = null;
79     private final static HashMap servletModuleInstanceHash = new HashMap();
80
81     public HttpSession session;
82
83     public void doGet(HttpServletRequest req, HttpServletResponse res)
84             throws ServletException, IOException {
85         doPost(req, res);
86     }
87
88     public void doPost(HttpServletRequest req, HttpServletResponse res)
89             throws ServletException, IOException, UnavailableException {
90
91
92
93         long startTime = System.currentTimeMillis();
94         long sessionConnectTime = 0;
95         EntityUsers userEntity;
96         String http = "";
97
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) {
101             getConfig(req);
102         }
103         MirConfig.setServletName(getServletName());
104
105         //*** test
106        // Log.info(this, "blalalala");
107
108         session = req.getSession(true);
109         userEntity = (EntityUsers) session.getAttribute("login.uid");
110
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");
115
116         checkLanguage(session, req);
117
118         /** @todo for cleanup and readability this should be moved to
119          *  method loginIfNecessary() */
120
121         if (moduleName!=null && moduleName.equals("direct")) {
122           //...
123         }
124
125         // Authentifizierung
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());
135                 return;
136             }
137             else if (moduleName!=null && moduleName.equals("login")) {
138                 // login successful
139
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");
144
145                 if (target != null) {
146                     theLog.printDebugInfo("Redirect: " + target);
147                     int serverPort = req.getServerPort();
148                     String redirect = "";
149                     String redirectString = "";
150
151
152                     if (serverPort == 80) {
153                         redirect = res.encodeURL(http + "://" + req.getServerName() + target);
154                         redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
155                                 + redirect
156                                 + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
157                     }
158                     else {
159                         redirect = res.encodeURL(http + "://" + req.getServerName() + ":" + req.getServerPort() + target);
160                         redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
161                                 + redirect
162                                 + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
163                     }
164                     res.getWriter().println(redirectString);
165
166
167                     //res.sendRedirect(redirect);
168
169                 }
170                 else {
171                     // redirecting to default target
172                     theLog.printDebugInfo("--login: no target - redirecting to default");
173                     _sendStartPage(res, req, res.getWriter(), userEntity);
174                 }
175                 return;
176             } // if login succesful
177         } // if login
178
179         if (moduleName != null && moduleName.equals("logout")) {
180             theLog.printDebugInfo("--logout");
181             session.invalidate();
182
183             //session = req.getSession(true);
184             //checkLanguage(session, req);
185             _sendLoginPage(res, req, res.getWriter());
186             return;
187         }
188
189         // Check if authed!
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);
198             }
199             _sendLoginPage(res, req, res.getWriter());
200             return;
201         }
202
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);
207             return;
208         }
209         // end of auth
210
211         // From now on regular dispatching...
212         try {
213             // get servletmodule by parameter and continue with dispacher
214             ServletModule smod = getServletModuleForName(moduleName);
215             ServletModuleDispatch.dispatch(smod, req, res);
216         }
217         catch (ServletModuleException e) {
218             handleError(req, res, res.getWriter(),
219                         "ServletException in Module " + moduleName + " -- " + e.getMessage());
220         }
221         catch (ServletModuleUserException e) {
222             handleUserError(req, res, res.getWriter(), e.getMessage());
223         }
224
225         // timing...
226         sessionConnectTime = System.currentTimeMillis() - startTime;
227         theLog.printInfo("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
228     }
229
230
231     /**
232      *  Private method getServletModuleForName returns ServletModule
233      *  from Cache
234      *
235      * @return ServletModule
236      *
237      */
238     private static ServletModule getServletModuleForName(String moduleName)
239             throws ServletModuleException {
240
241         // Instance in Map ?
242         if (!servletModuleInstanceHash.containsKey(moduleName)) {
243             // was not found in hash...
244             try {
245                 Class theServletModuleClass = null;
246                 try {
247                     // first we try to get ServletModule from stern.che3.servlet
248                     theServletModuleClass = Class.forName("mircoders.servlet.ServletModule" + moduleName);
249                 }
250                 catch (ClassNotFoundException e) {
251                     // on failure, we try to get it from lib-layer
252                     theServletModuleClass = Class.forName("mir.servlet.ServletModule" + moduleName);
253                 }
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);
258                 return smod;
259             }
260             catch (Exception e) {
261                 throw new ServletModuleException("*** error resolving classname for " +
262                                                  moduleName + " -- " + e.getMessage());
263             }
264         }
265         else
266             return (ServletModule) servletModuleInstanceHash.get(moduleName);
267     }
268
269
270     private void handleError(HttpServletRequest req, HttpServletResponse res,
271                              PrintWriter out, String errorString) {
272
273         try {
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));
279             out.close();
280         }
281         catch (Exception e) {
282           e.printStackTrace(System.out);
283           System.err.println("Error in ErrorTemplate: " + e.getMessage());
284         }
285     }
286
287     private void handleUserError(HttpServletRequest req, HttpServletResponse res,
288                                  PrintWriter out, String errorString) {
289         try {
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));
296             out.close();
297         }
298         catch (Exception e) {
299             System.err.println("Error in UserErrorTemplate");
300         }
301
302     }
303
304     /**
305      *  evaluate login for user / password
306      */
307     protected EntityUsers allowedUser(String user, String password) {
308         try {
309             if (usersModule == null) usersModule = new ModuleUsers(DatabaseUsers.getInstance());
310             return usersModule.getUserForLogin(user, password);
311         }
312         catch (Exception e) {
313             theLog.printDebugInfo(e.getMessage());
314             e.printStackTrace();
315             return null;
316         }
317     }
318
319     // Redirect-methods
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);
325         try {
326             //theLog.printDebugInfo("login: "+lang);
327             //if(lang==null){
328             //  lang=getAcceptLanguage(req);
329             //}
330             SimpleHash mergeData = new SimpleHash();
331             mergeData.put("session", sessionUrl);
332             HTMLTemplateProcessor.process(res, loginTemplate, mergeData, out, getLocale(req));
333         }
334         catch (HTMLParseException e) {
335             handleError(req, res, out, "Error in logintemplate.");
336         }
337     }
338
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("");
342         try {
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));
349
350             mergeData.put("articletypes", DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
351
352 /*
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();
357
358               SimpleList producerVerbs = new SimpleList();
359               Iterator j = ((ProducerFactory) entry.getValue()).verbs();
360               while (j.hasNext()) {
361                 producerVerbs.add((String) j.next());
362               }
363
364               SimpleHash producerData = new SimpleHash();
365               producerData.put("key", (String) entry.getKey());
366               producerData.put("verbs", producerVerbs);
367
368               producersData.add(producerData);
369             }
370             mergeData.put("producers", producersData);
371  */
372
373
374             HTMLTemplateProcessor.process(res, startTemplate, mergeData, out, getLocale(req));
375         }
376         catch (Exception e) {
377             e.printStackTrace(System.out);
378             handleError(req, res, out, "error while trying to send startpage. " + e.getMessage());
379         }
380     }
381
382     public String getServletInfo() {
383         return "Mir "+MirConfig.getProp("Mir.Version");
384     }
385
386     private void checkLanguage(HttpSession session, HttpServletRequest req) {
387
388         // a lang parameter always sets the language
389         String lang = req.getParameter("lang");
390         if (lang != null) {
391             theLog.printInfo("selected language "+lang+" overrides accept-language");
392             setLanguage(session, lang);
393             setLocale(session, new Locale(lang, ""));
394         }
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());
400         }
401     }
402 }
403