X-Git-Url: http://erislabs.net/gitweb/?a=blobdiff_plain;f=source%2FMir.java;h=91be32de1f460388b90c869d812d828da6df6589;hb=63e0ee1fb8038eb6d8f0190cf38c3b3ab2727216;hp=e7f306c65914f7c617a4363d544eff75a4722fc9;hpb=1a5a73406ec9c167c922418bef68a0e784eb65e4;p=mir.git diff --git a/source/Mir.java b/source/Mir.java index e7f306c6..91be32de 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -18,104 +18,71 @@ * 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 java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.Method; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Vector; - -import javax.servlet.ServletException; -import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - +import mir.bundle.Bundle; import mir.config.MirPropertiesConfiguration; -import mir.generator.FreemarkerGenerator; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; -import mir.servlet.AbstractServlet; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; +import mir.servlet.*; import mir.util.ExceptionFunctions; import mir.util.StringRoutines; +import mir.log.LoggerWrapper; import mircoders.entity.EntityUsers; import mircoders.global.MirGlobal; -import mircoders.module.ModuleMessage; import mircoders.module.ModuleUsers; -import mircoders.storage.DatabaseArticleType; -import mircoders.storage.DatabaseMessages; -import mircoders.storage.DatabaseUsers; - -import org.apache.struts.util.MessageResources; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModel; - +import mircoders.servlet.ServletHelper; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.UnavailableException; +import javax.servlet.http.*; +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.util.*; +import multex.Failure; /** * Mir.java - main servlet, that dispatches to servletmodules - * - * @author $Author: idfx $ - * @version $Id: Mir.java,v 1.39 2003/03/15 02:07:35 idfx Exp $ - * */ public class Mir extends AbstractServlet { private static ModuleUsers usersModule = null; - private static ModuleMessage messageModule = null; private final static Map servletModuleInstanceHash = new HashMap(); + private static Locale fallbackLocale = null; - //I don't know about making this static cause it removes the - //possibility to change the config on the fly.. -mh private static List loginLanguages = null; - public HttpSession session; - protected TemplateModel getLoginLanguages() throws ServletException { + private List getLoginLanguages() throws Failure { synchronized (Mir.class) { try { if (loginLanguages == null) { - MessageResources messageResources2 = - MessageResources.getMessageResources("bundles.admin"); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.adminlocal"); List languages = - StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault( - "Mir.Login.Languages", "en"), ";"); + StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";"); - loginLanguages = new Vector(); + loginLanguages = new ArrayList(); Iterator i = languages.iterator(); while (i.hasNext()) { String code = (String) i.next(); - Locale locale = new Locale(code, ""); - String name = messageResources.getMessage(locale, "languagename"); + + 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 = messageResources2.getMessage(locale, "languagename"); + name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST); } if (name == null) { @@ -129,19 +96,23 @@ public class Mir extends AbstractServlet { } } - return FreemarkerGenerator.makeAdapter(loginLanguages); + return loginLanguages; } catch (Throwable t) { - throw new ServletException(t.getMessage()); + throw new Failure("Error while retrieving the available login languages", t); } } } - // FIXME: this should probalby go into AbstractServlet so it can be used in - // OpenMir as well -mh + public void init(ServletConfig config) throws ServletException { + super.init(config); + + usersModule = new ModuleUsers(); + } + protected String getDefaultLanguage(HttpServletRequest aRequest) { String defaultlanguage = - MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", ""); + MirGlobal.config().getString("Mir.Login.DefaultLanguage", ""); if (defaultlanguage.length() == 0) { Locale locale = aRequest.getLocale(); @@ -151,172 +122,131 @@ public class Mir extends AbstractServlet { return defaultlanguage; } - public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletException, IOException, UnavailableException { - long startTime = System.currentTimeMillis(); - long sessionConnectTime = 0; - EntityUsers userEntity; - String http = ""; - - configuration.addProperty("ServletName", getServletName()); + 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()); + } - session = aRequest.getSession(true); - userEntity = (EntityUsers) session.getAttribute("login.uid"); + return fallbackLocale; + } - if (aRequest.getServerPort() == 443) { - http = "https"; - } else { - http = "http"; - } + public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException { + try { + EntityUsers user = ServletHelper.getUser(aRequest); - //make sure client browsers don't cache anything - setNoCaching(aResponse); + String username = aRequest.getParameter("login"); + String password = aRequest.getParameter("password"); - //FIXME: this seems kind of hackish and only here because we can have - // default other than the one that the browser is set to. - Locale locale = new Locale(getDefaultLanguage(aRequest), ""); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.admin"); - String htmlcharset = messageResources.getMessage(locale, "htmlcharset"); + if (username != null && password != null) { + user = usersModule.getUserForLogin(username, password); - aResponse.setContentType("text/html; charset=" + htmlcharset); + if (user!=null) { + ServletHelper.setUser(aRequest, user); + usersModule.recordLogin(user); + aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId())); + } + } - String moduleName = aRequest.getParameter("module"); - checkLanguage(session, aRequest); + return user; + } + catch (Throwable t) { + t.printStackTrace(); - /** @todo for cleanup and readability this should be moved to - * method loginIfNecessary() */ - if ((moduleName != null) && moduleName.equals("direct")) { - //... + throw new ServletException(t.toString()); } + } - // Authentication - if (((moduleName != null) && moduleName.equals("login")) || - (userEntity == null)) { - String user = aRequest.getParameter("login"); - String passwd = aRequest.getParameter("password"); - logger.debug("--login: evaluating for user: " + user); - userEntity = allowedUser(user, passwd); + public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException { + try { + long startTime = System.currentTimeMillis(); + long sessionConnectTime = 0; - if (userEntity == null) { - // login failed: redirecting to login - logger.warn("--login: failed!"); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } else if ((moduleName != null) && moduleName.equals("login")) { - // login successful - logger.info("--login: successful! setting uid: " + userEntity.getId()); - session.setAttribute("login.uid", userEntity); - logger.debug("--login: trying to retrieve login.target"); - - String target = (String) session.getAttribute("login.target"); - - if (target != null) { - logger.debug("Redirect: " + target); - - int serverPort = aRequest.getServerPort(); - String redirect = ""; - String redirectString = ""; - - if (serverPort == 80) { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + target); - redirectString = - "going Mir"; - } else { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" + - aRequest.getServerPort() + target); - redirectString = - "going Mir"; - } + HttpSession session = aRequest.getSession(true); + setNoCaching(aResponse); + aResponse.setContentType("text/html; charset=" + + configuration. + getString("Mir.DefaultHTMLCharset", "UTF-8")); + + EntityUsers userEntity = checkCredentials(aRequest); - aResponse.getWriter().println(redirectString); + if (userEntity == null) { + String queryString = aRequest.getQueryString(); - //aResponse.sendRedirect(redirect); - } else { - // redirecting to default target - logger.debug("--login: no target - redirecting to default"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + 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); } - return; + _sendLoginPage(aResponse, aRequest); } - // if login succesful - } - // if login - - if ((moduleName != null) && moduleName.equals("logout")) { - logger.info("--logout"); - session.invalidate(); - - //session = aRequest.getSession(true); - //checkLanguage(session, aRequest); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + else { + String moduleName = aRequest.getParameter("module"); + checkLanguage(session, aRequest); - return; - } - - // Check if authed! - if (userEntity == null) { - // redirect to loginpage - String redirectString = aRequest.getRequestURI(); - String queryString = aRequest.getQueryString(); + if ( ( (moduleName == null) || moduleName.equals(""))) { + moduleName="Admin"; + } - if ((queryString != null) && !queryString.equals("")) { - redirectString += ("?" + aRequest.getQueryString()); - logger.debug("STORING: " + redirectString); - session.setAttribute("login.target", redirectString); - } - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + if (moduleName.equals("login")) { + String target = (String) session.getAttribute("login.target"); - return; - } + if (target != null) { + ServletHelper.redirect(aResponse, target); + } + else { + ServletHelper.redirect(aResponse, ""); + } + } + else if (moduleName.equals("logout")) { + logger.info(userEntity.getFieldValue("login") + " has logged out"); + session.invalidate(); + _sendLoginPage(aResponse, aRequest); + return; + } + else { + try { + ServletModule servletModule = getServletModuleForName(moduleName); + ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse); - // If no module is specified goto standard startpage - if ((moduleName == null) || moduleName.equals("")) { - logger.debug("no module: redirect to standardpage"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + sessionConnectTime = System.currentTimeMillis() - startTime; + logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); + } + catch (Throwable e) { + Throwable cause = ExceptionFunctions.traceCauseException(e); - return; - } + if (cause instanceof ServletModuleUserExc) + handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause); + else + handleError(aRequest, aResponse, cause); + } - // end of auth - // From now on regular dispatching... - try { - // get servletmodule by parameter and continue with dispacher - ServletModule smod = getServletModuleForName(moduleName); - ServletModuleDispatch.dispatch(smod, aRequest, aResponse); + if (aRequest.getParameter("killsession")!=null) + aRequest.getSession().invalidate(); + } + } } - catch (Throwable e) { - Throwable cause = ExceptionFunctions.traceCauseException(e); - - if (cause instanceof ServletModuleUserExc) - handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); - else - handleError(aRequest, aResponse, aResponse.getWriter(), cause); + catch (Throwable t) { + t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + throw new ServletException(t.toString()); } - - // timing... - sessionConnectTime = System.currentTimeMillis() - startTime; - logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); } /** - * Private method getServletModuleForName returns ServletModule - * from Cache - * - * @param moduleName - * @return ServletModule + * caching routine to get a module for a module name * + * @param moduleName the module name + * @return the requested module + * @throws ServletModuleExc */ + private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc { // Instance in Map ? if (!servletModuleInstanceHash.containsKey(moduleName)) { @@ -328,7 +258,8 @@ public class Mir extends AbstractServlet { // first we try to get ServletModule from stern.che3.servlet theServletModuleClass = Class.forName("mircoders.servlet.ServletModule" + moduleName); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { // on failure, we try to get it from lib-layer theServletModuleClass = Class.forName("mir.servlet.ServletModule" + moduleName); @@ -351,114 +282,82 @@ public class Mir extends AbstractServlet { } } - private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, - PrintWriter out, ServletModuleUserExc anException) { + private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) { try { logger.info("user error: " + anException.getMessage()); - SimpleHash modelRoot = new SimpleHash(); - MessageResources messages = MessageResources.getMessageResources("bundles.admin"); - modelRoot.put("errorstring", - new SimpleScalar( - messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) - )); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); - HTMLTemplateProcessor.process( - aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), - modelRoot, out, getLocale(aRequest)); - out.close(); - } - catch (Exception e) { - logger.error("Error in UserErrorTemplate"); - } - - } - private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - try { - logger.error("error: " + anException); - SimpleHash modelRoot = new SimpleHash(); - modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( - new GregorianCalendar()))); - HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), - modelRoot,out, getLocale(aRequest)); - out.close(); - } - catch (Exception e) { - logger.error("Error in ErrorTemplate"); - } - } + 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())); - /** - * evaluate login for user / password - */ - protected EntityUsers allowedUser(String user, String password) { - try { - if (usersModule == null) { - usersModule = new ModuleUsers(DatabaseUsers.getInstance()); + if (message==null) { + message = + defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())); } - return usersModule.getUserForLogin(user, password); - } - catch (Exception e) { - logger.debug(e.getMessage()); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + responseData.put("errorstring", message); + responseData.put("date", new GregorianCalendar().getTime()); - return null; + ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate")); + } + catch (Throwable e) { + logger.error("Error handling user error" + e.toString()); } } - // Redirect-methods - private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out) { - String loginTemplate = configuration.getString("Mir.LoginTemplate"); - String sessionUrl = aResponse.encodeURL(""); - + private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) { try { - SimpleHash mergeData = new SimpleHash(); - SimpleList languages = new SimpleList(); + logger.error("error: " + anException); - mergeData.put("session", sessionUrl); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); - mergeData.put("languages", getLoginLanguages()); + responseData.put("errorstring", anException.toString()); + responseData.put("date", new GregorianCalendar().getTime()); - HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out, - getLocale(aRequest)); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate")); } catch (Throwable e) { - handleError(aRequest, aResponse, out, e); + logger.error("Error handling error: " + e.toString()); + + try { + Throwable rootException = ExceptionFunctions.traceCauseException(anException); + + PrintWriter writer = aResponse.getWriter(); + writer.println("FATAL Error"); + writer.println("

" + rootException.toString()+"

"); + writer.println(""); + rootException.printStackTrace(writer); + writer.println(""); + writer.println(""); + writer.close(); + } + catch (Throwable t) { + + } } } - private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out, EntityUsers userEntity) { - String startTemplate = "templates/admin/start_admin.template"; - String sessionUrl = aResponse.encodeURL(""); + // Redirect-methods + private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) { + String loginTemplate = configuration.getString("Mir.LoginTemplate"); 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)); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - mergeData.put("articletypes", - DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20)); + responseData.put("defaultlanguage", getDefaultLanguage(aRequest)); + responseData.put("languages", getLoginLanguages()); - HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out, - getLocale(aRequest)); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate); } - catch (Exception e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - handleError(aRequest, aResponse, out, e); + catch (Throwable e) { + handleError(aRequest, aResponse, e); } } @@ -466,20 +365,21 @@ public class Mir extends AbstractServlet { return "Mir " + configuration.getString("Mir.Version"); } - private void checkLanguage(HttpSession session, HttpServletRequest aRequest) { - // a lang parameter always sets the language - String lang = aRequest.getParameter("language"); + private class SessionTracker implements HttpSessionBindingListener { + private String name; + private String id; - if (lang != null) { - logger.info("selected language " + lang + " overrides accept-language"); - setLanguage(session, lang); - setLocale(session, new Locale(lang, "")); + public SessionTracker(String aUserName, String anId) { + name = aUserName; + id = anId; } - // otherwise store language from accept header in session - else if (session.getAttribute("Language") == null) { - logger.info("accept-language is " + aRequest.getLocale().getLanguage()); - setLanguage(session, aRequest.getLocale().getLanguage()); - setLocale(session, aRequest.getLocale()); + + public void valueBound(HttpSessionBindingEvent anEvent) { + MirGlobal.registerLogin(name, id); + } + + public void valueUnbound(HttpSessionBindingEvent anEvent) { + MirGlobal.registerLogout(name, id); } } }