multiple file-editable directories
[mir.git] / source / Mir.java
index 61ba516..01af8f3 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;
@@ -47,6 +46,7 @@ import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
 import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityIteratorAdapter;
 import mir.generator.FreemarkerGenerator;
 import mir.log.LoggerWrapper;
 import mir.misc.HTMLTemplateProcessor;
@@ -56,14 +56,14 @@ 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.*;
 import mircoders.storage.DatabaseUsers;
 
 import org.apache.struts.util.MessageResources;
@@ -75,39 +75,35 @@ import freemarker.template.TemplateModel;
 
 
 
+
 /**
  * Mir.java - main servlet, that dispatches to servletmodules
  *
  * @author $Author: zapata $
- * @version $Id: Mir.java,v 1.36 2003/03/09 03:53:10 zapata Exp $
+ * @version $Id: Mir.java,v 1.46 2003/04/28 00:44:05 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();
 
@@ -145,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();
@@ -155,22 +151,29 @@ 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");
 
@@ -186,20 +189,19 @@ public class Mir extends AbstractServlet {
     //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");
+    String htmlcharset = "UTF-8";
+    try {
+      htmlcharset = MirPropertiesConfiguration.instance().getString("Mir.DefaultHTMLCharset");
+    }
+    catch (Throwable t) {
+    }
 
     aResponse.setContentType("text/html; charset=" + htmlcharset);
 
     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")) ||
@@ -215,7 +217,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);
@@ -356,20 +359,31 @@ public class Mir extends AbstractServlet {
       catch (Exception e) {
         throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
       }
-    } else {
+    }
+    else {
       return (ServletModule) servletModuleInstanceHash.get(moduleName);
     }
   }
 
   private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
-                               PrintWriter out, Throwable anException) {
+                               PrintWriter out, ServletModuleUserExc anException) {
     try {
       logger.info("user error: " + anException.getMessage());
       SimpleHash modelRoot = new SimpleHash();
-      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
+      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, aRequest.getLocale() );
+      HTMLTemplateProcessor.process(
+          aResponse,
+          MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
+          modelRoot,
+          null,
+          out,
+          getLocale(aRequest),
+          fallbackLocale);
       out.close();
     }
     catch (Exception e) {
@@ -386,8 +400,9 @@ 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, aRequest.getLocale());
+      HTMLTemplateProcessor.process(
+          aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
+          modelRoot,null,out, getLocale(aRequest), getFallbackLocale());
       out.close();
     }
     catch (Exception e) {
@@ -408,7 +423,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;
     }
@@ -429,8 +444,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);
@@ -439,27 +453,26 @@ 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("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(aResponse.getWriter(), mergeData, startTemplate);
     }
     catch (Exception e) {
       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
@@ -478,13 +491,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());
     }
   }
 }