* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two. You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries. If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so. If you do
- * not wish to do so, delete this exception statement from your version.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
*/
-import freemarker.template.SimpleList;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleScalar;
-import mir.misc.HTMLParseException;
-import mir.misc.HTMLTemplateProcessor;
-import mir.misc.MirConfig;
-import mir.misc.StringUtil;
+import mir.bundle.Bundle;
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
import mir.servlet.*;
-import mir.producer.*;
-
-import mircoders.global.*;
-import mircoders.localizer.*;
-import mircoders.entity.EntityUsers;
-import mircoders.module.ModuleMessage;
-import mircoders.module.ModuleUsers;
-import mircoders.storage.DatabaseArticleType;
-import mircoders.storage.DatabaseMessages;
-import mircoders.storage.DatabaseUsers;
+import mir.util.StringRoutines;
+import mir.util.ExceptionRoutines;
+import multex.Failure;
+import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
+import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
-import java.lang.reflect.Method;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Locale;
+import java.io.StringWriter;
import java.util.*;
-import mir.log.Log;
+import mircoders.module.ModuleUsers;
+import mircoders.global.MirGlobal;
+import mircoders.servlet.ServletHelper;
+import mircoders.entity.EntityUsers;
-/**
- * Mir.java - main servlet, that dispatches to servletmodules
- *
- * @author $Author: mh $
- * @version $Id: Mir.java,v 1.22 2002/11/04 04:35:20 mh Exp $
- *
- */
+public class Mir extends AbstractServlet {
+ private static ModuleUsers usersModule = null;
+ private static Locale fallbackLocale = null;
+ private static List loginLanguages = null;
-public class Mir extends AbstractServlet {
+ private List getLoginLanguages() throws Failure {
+ synchronized (Mir.class) {
+ try {
+ if (loginLanguages == null) {
+ List languages =
+ StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
- private static ModuleUsers usersModule = null;
- private static ModuleMessage messageModule = null;
- private final static HashMap servletModuleInstanceHash = new HashMap();
+ loginLanguages = new ArrayList();
- public HttpSession session;
+ Iterator i = languages.iterator();
- public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- doPost(req, res);
- }
+ while (i.hasNext()) {
+ String code = (String) i.next();
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException, UnavailableException {
+ Bundle bundle =
+ MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new String[] { code });
+ Bundle defaultBundle =
+ MirGlobal.getBundleFactory().getBundle("bundles/admin", new String[] { code });
+ String name = bundle.getValue("languagename", Collections.EMPTY_LIST);
+ if (name == null) {
+ name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST);
+ }
- long startTime = System.currentTimeMillis();
- long sessionConnectTime = 0;
- EntityUsers userEntity;
- String http = "";
+ if (name == null) {
+ name = code;
+ }
- // get the configration - this could conflict if 2 mirs are in the
- // VM maybe? to be checked. -mh
- if (getServletContext().getAttribute("mir.confed") == null) {
- getConfig(req);
+ Map record = new HashMap();
+ record.put("name", name);
+ record.put("code", code);
+ loginLanguages.add(record);
+ }
}
- MirConfig.setServletName(getServletName());
- //*** test
- // Log.info(this, "blalalala");
+ return loginLanguages;
+ }
+ catch (Throwable t) {
+ throw new Failure("Error while retrieving the available login languages", t);
+ }
+ }
+ }
+
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
- session = req.getSession(true);
- userEntity = (EntityUsers) session.getAttribute("login.uid");
+ usersModule = new ModuleUsers();
+ }
- if (req.getServerPort() == 443) http = "https"; else http = "http";
- res.setContentType("text/html; charset="
- +MirConfig.getProp("Mir.DefaultEncoding"));
- String moduleName = req.getParameter("module");
+ protected String getDefaultLanguage(HttpServletRequest aRequest) {
+ String defaultlanguage =
+ MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
- checkLanguage(session, req);
+ if (defaultlanguage.length() == 0) {
+ Locale locale = aRequest.getLocale();
+ defaultlanguage = locale.getLanguage();
+ }
- /** @todo for cleanup and readability this should be moved to
- * method loginIfNecessary() */
+ return defaultlanguage;
+ }
- if (moduleName!=null && moduleName.equals("direct")) {
- //...
- }
+ protected synchronized Locale getFallbackLocale() throws ServletException {
+ try {
+ if (fallbackLocale == null) {
+ fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
+ }
+ }
+ catch (Throwable t) {
+ throw new ServletException(t.getMessage());
+ }
- // Authentifizierung
- if ((moduleName != null && moduleName.equals("login")) || (userEntity==null)) {
- String user = req.getParameter("login");
- String passwd = req.getParameter("password");
- theLog.printDebugInfo("--login: evaluating for user: " + user);
- userEntity = allowedUser(user, passwd);
- if (userEntity == null) {
- // login failed: redirecting to login
- theLog.printWarning("--login: failed!");
- _sendLoginPage(res, req, res.getWriter());
- return;
- }
- else if (moduleName!=null && moduleName.equals("login")) {
- // login successful
-
- theLog.printInfo("--login: successful! setting uid: " + userEntity.getId());
- session.setAttribute("login.uid", userEntity);
- theLog.printDebugInfo("--login: trying to retrieve login.target");
- String target = (String) session.getAttribute("login.target");
-
- if (target != null) {
- theLog.printDebugInfo("Redirect: " + target);
- int serverPort = req.getServerPort();
- String redirect = "";
- String redirectString = "";
-
-
- if (serverPort == 80) {
- redirect = res.encodeURL(http + "://" + req.getServerName() + target);
- redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
- + redirect
- + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
- }
- else {
- redirect = res.encodeURL(http + "://" + req.getServerName() + ":" + req.getServerPort() + target);
- redirectString = "<html><head><meta http-equiv=refresh content=\"1;URL="
- + redirect
- + "\"></head><body>going <a href=\"" + redirect + "\">Mir</a></body></html>";
- }
- res.getWriter().println(redirectString);
-
-
- //res.sendRedirect(redirect);
-
- }
- else {
- // redirecting to default target
- theLog.printDebugInfo("--login: no target - redirecting to default");
- _sendStartPage(res, req, res.getWriter(), userEntity);
- }
- return;
- } // if login succesful
- } // if login
-
- if (moduleName != null && moduleName.equals("logout")) {
- theLog.printDebugInfo("--logout");
- session.invalidate();
-
- //session = req.getSession(true);
- //checkLanguage(session, req);
- _sendLoginPage(res, req, res.getWriter());
- return;
- }
+ return fallbackLocale;
+ }
- // Check if authed!
- if (userEntity == null) {
- // redirect to loginpage
- String redirectString = req.getRequestURI();
- String queryString = req.getQueryString();
- if (queryString != null && !queryString.equals("")) {
- redirectString += "?" + req.getQueryString();
- theLog.printDebugInfo("STORING: " + redirectString);
- session.setAttribute("login.target", redirectString);
- }
- _sendLoginPage(res, req, res.getWriter());
- return;
- }
+ public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {
+ try {
+ EntityUsers user = ServletHelper.getUser(aRequest);
- // If no module is specified goto standard startpage
- if (moduleName == null || moduleName.equals("")) {
- theLog.printDebugInfo("no module: redirect to standardpage");
- _sendStartPage(res, req, res.getWriter(), userEntity);
- return;
- }
- // end of auth
+ String username = aRequest.getParameter("login");
+ String password = aRequest.getParameter("password");
- // From now on regular dispatching...
- try {
- // get servletmodule by parameter and continue with dispacher
- ServletModule smod = getServletModuleForName(moduleName);
- ServletModuleDispatch.dispatch(smod, req, res);
- }
- catch (ServletModuleException e) {
- handleError(req, res, res.getWriter(),
- "ServletException in Module " + moduleName + " -- " + e.getMessage());
- }
- catch (ServletModuleUserException e) {
- handleUserError(req, res, res.getWriter(), e.getMessage());
+ if (username != null && password != null) {
+ user = usersModule.getUserForLogin(username, password);
+
+ if (user!=null) {
+ ServletHelper.setUser(aRequest, user);
+ usersModule.recordLogin(user);
+ aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId()));
}
+ }
- // timing...
- sessionConnectTime = System.currentTimeMillis() - startTime;
- theLog.printInfo("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
+ return user;
}
+ catch (Throwable t) {
+ throw new ServletException(t.getMessage());
+ }
+ }
+ public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {
+ try {
+ long startTime = System.currentTimeMillis();
+ long sessionConnectTime = 0;
- /**
- * Private method getServletModuleForName returns ServletModule
- * from Cache
- *
- * @return ServletModule
- *
- */
- private static ServletModule getServletModuleForName(String moduleName)
- throws ServletModuleException {
-
- // Instance in Map ?
- if (!servletModuleInstanceHash.containsKey(moduleName)) {
- // was not found in hash...
- try {
- Class theServletModuleClass = null;
- try {
- // first we try to get ServletModule from stern.che3.servlet
- theServletModuleClass = Class.forName("mircoders.servlet.ServletModule" + moduleName);
- }
- catch (ClassNotFoundException e) {
- // on failure, we try to get it from lib-layer
- theServletModuleClass = Class.forName("mir.servlet.ServletModule" + moduleName);
- }
- Method m = theServletModuleClass.getMethod("getInstance", null);
- ServletModule smod = (ServletModule) m.invoke(null, null);
- // we put it into map for further reference
- servletModuleInstanceHash.put(moduleName, smod);
- return smod;
- }
- catch (Exception e) {
- throw new ServletModuleException("*** error resolving classname for " +
- moduleName + " -- " + e.getMessage());
- }
- }
- else
- return (ServletModule) servletModuleInstanceHash.get(moduleName);
- }
+ HttpSession session = aRequest.getSession(true);
+ setNoCaching(aResponse);
+ aResponse.setContentType("text/html; charset=" +
+ configuration.
+ getString("Mir.DefaultHTMLCharset", "UTF-8"));
+ EntityUsers userEntity = checkCredentials(aRequest);
- private void handleError(HttpServletRequest req, HttpServletResponse res,
- PrintWriter out, String errorString) {
+ if (userEntity == null) {
+ String queryString = aRequest.getQueryString();
- try {
- theLog.printError(errorString);
- SimpleHash modelRoot = new SimpleHash();
- modelRoot.put("errorstring", new SimpleScalar(errorString));
- modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
- HTMLTemplateProcessor.process(res, MirConfig.getProp("Mir.ErrorTemplate"), modelRoot, out, getLocale(req));
- out.close();
+ if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&
+ (aRequest.getParameter("module")==null ||
+ (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {
+ session.setAttribute("login.target", queryString);
}
- catch (Exception e) {
- e.printStackTrace(System.out);
- System.err.println("Error in ErrorTemplate: " + e.getMessage());
- }
- }
- private void handleUserError(HttpServletRequest req, HttpServletResponse res,
- PrintWriter out, String errorString) {
- try {
- theLog.printError(errorString);
- SimpleHash modelRoot = new SimpleHash();
- modelRoot.put("errorstring", new SimpleScalar(errorString));
- modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
- HTMLTemplateProcessor.process(res, MirConfig.getProp("Mir.UserErrorTemplate"),
- modelRoot, out, getLocale(req));
- out.close();
- }
- catch (Exception e) {
- System.err.println("Error in UserErrorTemplate");
+ _sendLoginPage(aResponse, aRequest);
+ }
+ else {
+ String moduleName = aRequest.getParameter("module");
+ checkLanguage(session, aRequest);
+
+ if ( ( (moduleName == null) || moduleName.equals(""))) {
+ moduleName="Admin";
}
- }
+ if (moduleName.equals("login")) {
+ String target = (String) session.getAttribute("login.target");
- /**
- * evaluate login for user / password
- */
- protected EntityUsers allowedUser(String user, String password) {
- try {
- if (usersModule == null) usersModule = new ModuleUsers(DatabaseUsers.getInstance());
- return usersModule.getUserForLogin(user, password);
+ if (target != null) {
+ ServletHelper.redirect(aResponse, target);
+ }
+ else {
+ ServletHelper.redirect(aResponse, "");
+ }
}
- catch (Exception e) {
- theLog.printDebugInfo(e.getMessage());
- e.printStackTrace();
- return null;
+ else if (moduleName.equals("logout")) {
+ logger.info(userEntity.getFieldValue("login") + " has logged out");
+ session.invalidate();
+ _sendLoginPage(aResponse, aRequest);
+ return;
}
- }
-
- // Redirect-methods
- private void _sendLoginPage(HttpServletResponse res, HttpServletRequest req, PrintWriter out) {
- String loginTemplate = MirConfig.getProp("Mir.LoginTemplate");//"login.template";
- // theLog.printDebugInfo("login template: "+loginTemplate);
- String sessionUrl = res.encodeURL("");
- //session = req.getSession(true);
- try {
- //theLog.printDebugInfo("login: "+lang);
- //if(lang==null){
- // lang=getAcceptLanguage(req);
- //}
- SimpleHash mergeData = new SimpleHash();
- mergeData.put("session", sessionUrl);
- HTMLTemplateProcessor.process(res, loginTemplate, mergeData, out, getLocale(req));
- }
- catch (HTMLParseException e) {
- handleError(req, res, out, "Error in logintemplate.");
+ else {
+ try {
+ AdminServletModule servletModule = getServletModuleForName(moduleName);
+ servletModule.handleRequest(aRequest, aResponse);
+
+ sessionConnectTime = System.currentTimeMillis() - startTime;
+ logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
+ }
+ catch (Throwable e) {
+ Throwable cause = ExceptionRoutines.traceCauseException(e);
+
+ if (cause instanceof ServletModuleUserExc)
+ handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
+ else
+ handleError(aRequest, aResponse, cause);
+ }
+
+ if (aRequest.getParameter("killsession")!=null)
+ aRequest.getSession().invalidate();
}
+ }
+ }
+ catch (Throwable t) {
+ throw new ServletException(t.toString());
+ }
+ }
+
+ /**
+ * caching routine to get a module for a module name
+ *
+ * @param aModuleName the module name
+ * @return the requested module
+ * @throws ServletModuleExc
+ */
+ private static AdminServletModule getServletModuleForName(String aModuleName) throws ServletModuleExc {
+ return ServletHelper.getServletModule(aModuleName);
+ }
+
+ private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
+ try {
+ logger.info("user error: " + anException.getMessage());
+
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+ Bundle bundle =
+ MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new
+ String[] { getLocale(aRequest).getLanguage() });
+ Bundle defaultBundle =
+ MirGlobal.getBundleFactory().getBundle("bundles/admin", new
+ String[] { getLocale(aRequest).getLanguage() });
+ String message =
+ bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
+
+ if (message==null) {
+ message =
+ defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()));
+ }
+
+ responseData.put("errorstring", message);
+ responseData.put("date", new GregorianCalendar().getTime());
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));
}
+ catch (Throwable e) {
+ logger.error("Error handling user error" + e.toString());
+ }
+ }
- private void _sendStartPage(HttpServletResponse res, HttpServletRequest req, PrintWriter out, EntityUsers userEntity) {
- String startTemplate = "templates/admin/start_admin.template";
- String sessionUrl = res.encodeURL("");
- try {
- // merge with logged in user and messages
- SimpleHash mergeData = new SimpleHash();
- mergeData.put("session", sessionUrl);
- mergeData.put("login_user", userEntity);
- if (messageModule == null) messageModule = new ModuleMessage(DatabaseMessages.getInstance());
- mergeData.put("messages", messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
+ private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {
+ try {
+ logger.error("error: " + anException);
- mergeData.put("articletypes", DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
-/*
- SimpleList producersData = new SimpleList();
- Iterator i = MirGlobal.localizer().producers().factories().entrySet().iterator();
- while (i.hasNext()) {
- Map.Entry entry = (Map.Entry) i.next();
-
- SimpleList producerVerbs = new SimpleList();
- Iterator j = ((ProducerFactory) entry.getValue()).verbs();
- while (j.hasNext()) {
- producerVerbs.add((String) j.next());
- }
-
- SimpleHash producerData = new SimpleHash();
- producerData.put("key", (String) entry.getKey());
- producerData.put("verbs", producerVerbs);
-
- producersData.add(producerData);
- }
- mergeData.put("producers", producersData);
- */
+ responseData.put("errorstring", anException.toString());
+ StringWriter writer = new StringWriter();
+ anException.printStackTrace(new PrintWriter(writer));
+ responseData.put("stacktrace", writer.toString());
+ responseData.put("date", new GregorianCalendar().getTime());
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
+ }
+ catch (Throwable e) {
+ logger.error("Error handling error: " + e.toString());
+
+ try {
+ Throwable rootException = ExceptionRoutines.traceCauseException(anException);
+
+ PrintWriter writer = aResponse.getWriter();
+ writer.println("<html><head><title>FATAL Error</title><body>");
+ writer.println("<h1>" + rootException.toString()+"</h1>");
+ writer.println("<code>");
+ rootException.printStackTrace(writer);
+ writer.println("</code>");
+ writer.println("</body></html>");
+ writer.close();
+ }
+ catch (Throwable t) {
+
+ }
+ }
+ }
- HTMLTemplateProcessor.process(res, startTemplate, mergeData, out, getLocale(req));
- }
- catch (Exception e) {
- e.printStackTrace(System.out);
- handleError(req, res, out, "error while trying to send startpage. " + e.getMessage());
- }
+ // Redirect-methods
+ private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {
+ String loginTemplate = configuration.getString("Mir.LoginTemplate");
+
+ try {
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+ responseData.put("defaultlanguage", getDefaultLanguage(aRequest));
+ responseData.put("languages", getLoginLanguages());
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);
}
+ catch (Throwable e) {
+ handleError(aRequest, aResponse, e);
+ }
+ }
+
+ public String getServletInfo() {
+ return "Mir " + configuration.getString("Mir.Version");
+ }
- public String getServletInfo() {
- return "Mir "+MirConfig.getProp("Mir.Version");
+ private class SessionTracker implements HttpSessionBindingListener {
+ private String name;
+ private String id;
+
+ public SessionTracker(String aUserName, String anId) {
+ name = aUserName;
+ id = anId;
}
- private void checkLanguage(HttpSession session, HttpServletRequest req) {
+ public void valueBound(HttpSessionBindingEvent anEvent) {
+ MirGlobal.registerLogin(name, id);
+ }
- // a lang parameter always sets the language
- String lang = req.getParameter("lang");
- if (lang != null) {
- theLog.printInfo("selected language "+lang+" overrides accept-language");
- setLanguage(session, lang);
- setLocale(session, new Locale(lang, ""));
- }
- // otherwise store language from accept header in session
- else if (session.getAttribute("Language") == null) {
- theLog.printInfo("accept-language is "+req.getLocale().getLanguage());
- setLanguage(session, req.getLocale().getLanguage());
- setLocale(session, req.getLocale());
- }
+ public void valueUnbound(HttpSessionBindingEvent anEvent) {
+ MirGlobal.registerLogout(name, id);
}
+ }
}
-