support for galego (galician)
[mir.git] / source / Mir.java
index 62ae28f..c67ecfc 100755 (executable)
  * 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;
@@ -39,7 +38,6 @@ 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;
@@ -47,13 +45,13 @@ import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
 import org.apache.struts.util.MessageResources;
-
 import freemarker.template.SimpleHash;
 import freemarker.template.SimpleList;
 import freemarker.template.SimpleScalar;
 import freemarker.template.TemplateModel;
 
 import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityIteratorAdapter;
 import mir.generator.FreemarkerGenerator;
 import mir.log.LoggerWrapper;
 import mir.misc.HTMLTemplateProcessor;
@@ -63,14 +61,16 @@ import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleDispatch;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleUserExc;
+import mir.util.CachingRewindableIterator;
 import mir.util.ExceptionFunctions;
 import mir.util.StringRoutines;
 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.servlet.ServletHelper;
+import mircoders.servlet.ServletModuleFileEdit;
+import mircoders.servlet.ServletModuleLocalizer;
 import mircoders.storage.DatabaseUsers;
 
 
@@ -80,35 +80,30 @@ import mircoders.storage.DatabaseUsers;
  * Mir.java - main servlet, that dispatches to servletmodules
  *
  * @author $Author: zapata $
- * @version $Id: Mir.java,v 1.37 2003/03/09 05:52:12 zapata Exp $
+ * @version $Id: Mir.java,v 1.48 2003/05/01 01:42:11 zapata 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;
-
-  public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse)
-    throws ServletException, IOException {
-    doPost(aRequest, aResponse);
-  }
 
   protected TemplateModel getLoginLanguages() throws ServletException {
     synchronized (Mir.class) {
       try {
         if (loginLanguages == null) {
-          MessageResources messageResources2 =
-            MessageResources.getMessageResources("bundles.admin");
           MessageResources messageResources =
             MessageResources.getMessageResources("bundles.adminlocal");
+          MessageResources messageResources2 =
+            MessageResources.getMessageResources("bundles.admin");
+
           List languages =
-            StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault(
-                "Mir.Login.Languages", "en"), ";");
+            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
 
           loginLanguages = new Vector();
 
@@ -146,7 +141,7 @@ public class Mir extends AbstractServlet {
   // OpenMir as well -mh
   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();
@@ -156,55 +151,51 @@ public class Mir extends AbstractServlet {
     return defaultlanguage;
   }
 
-  public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse)
+  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());
+    }
+
+    return fallbackLocale;
+  }
+
+  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
     throws ServletException, IOException, UnavailableException {
     long startTime = System.currentTimeMillis();
     long sessionConnectTime = 0;
     EntityUsers userEntity;
+    HttpSession session;
     String http = "";
 
-    if ((configuration.getString("RootUri") == null) ||
-        configuration.getString("RootUri").equals("")) {
-      configuration.setProperty("RootUri", aRequest.getContextPath());
-    }
-
     configuration.addProperty("ServletName", getServletName());
 
-    //*** test
-    // Log.info(this, "blalalala");
     session = aRequest.getSession(true);
     userEntity = (EntityUsers) session.getAttribute("login.uid");
 
     if (aRequest.getServerPort() == 443) {
       http = "https";
-    } else {
+    }
+    else {
       http = "http";
     }
 
-    //make sure client browsers don't cache anything
     setNoCaching(aResponse);
 
-    //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");
 
-    aResponse.setContentType("text/html; charset=" + htmlcharset);
+    aResponse.setContentType("text/html; charset=" +
+        configuration.getString("Mir.DefaultHTMLCharset", "UTF-8"));
 
     String moduleName = aRequest.getParameter("module");
     checkLanguage(session, aRequest);
 
-    /** @todo for cleanup and readability this should be moved to
-     *  method loginIfNecessary() */
-    if ((moduleName != null) && moduleName.equals("direct")) {
-      //...
-    }
-
     // Authentication
-    if (((moduleName != null) && moduleName.equals("login")) ||
-        (userEntity == null)) {
+    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);
@@ -216,7 +207,8 @@ public class Mir extends AbstractServlet {
         _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
 
         return;
-      } else if ((moduleName != null) && moduleName.equals("login")) {
+      }
+      else if ((moduleName != null) && moduleName.equals("login")) {
         // login successful
         logger.info("--login: successful! setting uid: " + userEntity.getId());
         session.setAttribute("login.uid", userEntity);
@@ -267,8 +259,6 @@ public class Mir extends AbstractServlet {
       logger.info("--logout");
       session.invalidate();
 
-      //session = aRequest.getSession(true);
-      //checkLanguage(session, aRequest);
       _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
 
       return;
@@ -280,9 +270,8 @@ public class Mir extends AbstractServlet {
       String redirectString = aRequest.getRequestURI();
       String queryString = aRequest.getQueryString();
 
-      if ((queryString != null) && !queryString.equals("")) {
+      if ((queryString != null) && queryString.length()!=0) {
         redirectString += ("?" + aRequest.getQueryString());
-        logger.debug("STORING: " + redirectString);
         session.setAttribute("login.target", redirectString);
       }
 
@@ -293,14 +282,12 @@ public class Mir extends AbstractServlet {
 
     // If no module is specified goto standard startpage
     if ((moduleName == null) || moduleName.equals("")) {
-      logger.debug("no module: redirect to standardpage");
+//      logger.debug("no module: redirect to standardpage");
       _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
 
       return;
     }
 
-    // end of auth
-    // From now on regular dispatching...
     try {
       // get servletmodule by parameter and continue with dispacher
       ServletModule smod = getServletModuleForName(moduleName);
@@ -375,12 +362,17 @@ public class Mir extends AbstractServlet {
           ));
       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
       HTMLTemplateProcessor.process(
-          aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
-          modelRoot, out, getLocale(aRequest));
+          aResponse,
+          MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
+          modelRoot,
+          null,
+          out,
+          getLocale(aRequest),
+          fallbackLocale);
       out.close();
     }
-    catch (Exception e) {
-      logger.error("Error in UserErrorTemplate");
+    catch (Throwable e) {
+      logger.error("Error handling user error" + e.toString());
     }
 
   }
@@ -393,12 +385,13 @@ public class Mir extends AbstractServlet {
       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));
+      HTMLTemplateProcessor.process(
+          aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
+          modelRoot,null,out, getLocale(aRequest), getFallbackLocale());
       out.close();
     }
-    catch (Exception e) {
-      logger.error("Error in ErrorTemplate");
+    catch (Throwable e) {
+      logger.error("Error handling error: " + e.toString());
     }
   }
 
@@ -415,7 +408,7 @@ public class Mir extends AbstractServlet {
     }
     catch (Exception e) {
       logger.debug(e.getMessage());
-      e.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
 
       return null;
     }
@@ -436,8 +429,7 @@ public class Mir extends AbstractServlet {
       mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
       mergeData.put("languages", getLoginLanguages());
 
-      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,
-        getLocale(aRequest));
+      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale());
     }
     catch (Throwable e) {
       handleError(aRequest, aResponse, out, e);
@@ -446,27 +438,27 @@ public class Mir extends AbstractServlet {
 
   private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
     PrintWriter out, EntityUsers userEntity) {
-    String startTemplate = "templates/admin/start_admin.template";
+    String startTemplate = configuration.getString("Mir.StartTemplate");
     String sessionUrl = aResponse.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());
-      }
-
+      Map mergeData = ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale()}, "bundles.admin", "bundles.adminlocal");
       mergeData.put("messages",
-        messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
+             new CachingRewindableIterator(
+               new EntityIteratorAdapter( "", "webdb_create desc", 10,
+                 MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
+
+      mergeData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
+      mergeData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
 
-      mergeData.put("articletypes",
-        DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
+      mergeData.put("searchvalue", null);
+      mergeData.put("searchfield", null);
+      mergeData.put("searchispublished", null);
+      mergeData.put("searcharticletype", null);
+      mergeData.put("searchorder", null);
+      mergeData.put("selectarticleurl", null);
 
-      HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,
-        getLocale(aRequest));
+      ServletHelper.generateResponse(out, mergeData, startTemplate);
     }
     catch (Exception e) {
       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
@@ -485,13 +477,11 @@ public class Mir extends AbstractServlet {
     if (lang != null) {
       logger.info("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) {
+    else if (session.getAttribute("language") == null) {
       logger.info("accept-language is " + aRequest.getLocale().getLanguage());
       setLanguage(session, aRequest.getLocale().getLanguage());
-      setLocale(session, aRequest.getLocale());
     }
   }
 }